Skip to content

JavaScript Basics

Nikolina Djekic edited this page Oct 3, 2019 · 1 revision

JavaScript CheatSheet

by Ninna

Table of Contents

  1. Shortcuts
  2. Variables
  3. Data Types
  4. Truthy and Falsy Values
  5. Operators
  6. Decision making
  7. Funcions
  8. Arrays
  9. Objects
  10. Loops
  11. Hoisting Scope and This

Shortcuts Atom and Browser

  1. Ctrl+Shift+J otvara console u Chrome-u
  2. cl - console.log(obj);
  3. al - alert('msg');
  4. pm - prompt('msg');
  5. fun - function block

Variables and Comments

  • Single line comments //

  • Multi line comments /**/

  • Always use camelCase

  • Only can start with letter, $ or underscore

  • Cannot give variables reserved names

  • Declare multiple variables in one line and assign values later

      var job, isMarried;
      job = 'programmer';
      isMarried = true;
  • When we want to change value of any variable we don't need to use var keyword, but only name and new value

  • Concatenation is done with + sign

  • Multiple assignment of value can be done by simply typing

     var x, y;
     //Check Operators, Table of Precendece for Assignment Operator '='
     x = y = (3 + 5) / 2;

Data types-Primitive

  1. Number - floating point, decimals, integers
  2. String - sequence of characters used for text
  3. Boolean - true/false
  4. Undefined - variable does not have a value yet
  5. Null - non existant

Truthy and Falsy values

  1. Falsy values - return false when evalueted in if/else conditions
    • Undefined
    • Null
    • 0 - avoid by adding condition that variable === 0 when true
    • ''
    • NaN
  2. Thruty values - return true when evalueted in if/else conditions
    • all not falsy values

Operators

  1. Math Operators - returns result

    • + - * /
  2. Logical Operators - returns true, false

    • <, >=, <=, >
  3. typeof Operator - returns type of variable

  4. Table of precedence of operators

  5. Assignment Operators Short version for adding same variable +-*/ and =

       x = x + 2;  ==> x += 2;
       x = x * 2;  ==> x *= 2;
       x = x / 2;  ==> x /= 2;
       x = x - 2;  ==> x -= 2;
  6. Increment Operator ++ or --

       x = x + 1;  ==> x++;
       x = x - 1;  ==> x--;
  7. Boolean logic

    • AND & & true if all are true
    • OR || true if one is true
    • NOT ! inverts true/false value
  8. Ternary operator used for making if/else statements in one line. Can be assigned to variable.

     condition ? //statement_if_is_true : //statement_if_is_false;
     var name = condition ? //statement_if_is_true : //statement_if_is_false;
  9. == vs ===

    • == is less strict, it transforms data type in order to make it true 23 == '23';
    • === does data type comparison -> data type must be same in order to be true 23 !== '23';

Decision making if/elseif, switch

  1. If/elseif has this structure:
  if (condition1) {
    //statement1;
  } else if (condition2) {
    //statement2;
  } else if (condition3) {
    //statement3;
  } else {
    //statementN;
  }
  1. Switch statements, if we work with ranges we need to put true instead of valiable

       switch (variable) {
         case expression1:
         case expression2:
           //statement1
           break;
         case expression3:
           //statement2
           break;
         default:
           //statement default
       }

Functions

  1. Declaring a function statement(they do actions- don't produce any immediate value):.

       function functionName(arg1, arg2){
         //what function does
         //return
       }
  2. Calling the function

       functionName(arg1, arg2);
  3. Declaring a function expression (anything that produces immediate result):

       var functionName = function(arg1, arg2) {
         //what function does
         //return
       }

Arrays

  1. Two ways of creating an array

      var arrName = [element1, element2];
      //or
      var arrName = new Array(element1, element2);
  2. Accessing the array or its [elements]

      arrName[index];
  3. Usefull array functions and methods

     //number of elements
       arrName.length;
     //add to end of array
       arrName.push(element);
     //or
       arrName[arrName.length] = element;
     //add to the begining of the array
       arrName.unshift(element);
     //remove element from the end of the array
       arrName.pop();
     //remove element from the begining of the array
       arrName.shift();
     //return the position of the argument that we pass inside array -> **returns -1** if there is no such element
       arrName.indexOf(element);

Objects

  1. Used for grouping variables which go together in no particular order

  2. Defining object

     var objName = {
       keyString: 'value',
       keyNumber: 192,
       keyArray: [],
       keyObject: {
         keyOfInsideObject: 'value'
       }
       funct: function(Arg){
         return something;
       }
     }
     //or
     var jane = new Object();
     jane.name = 'Jane';
     jane.birthYear = 1992;
     jane[''lastaAme] = 'Austin';
  3. Defining objects as function constructor, always Capital Letter

     var Name = function(arguments){
       this.arg1 = arg1;
       this.arg2 = arg2;
     }
     //popunjavanje
     var objName = new Name(arg1, arg2);
    
     //dodavanje metoda na prototip
     Name.prototype.functionName = function () {
       //do anything
       };
     // dodavanje propertija na prototip --> Svi se prezivaju smith! Not common
     Name.prototype.lastName = 'Smith'
    • new creates new empty Object and this se odnosi na ono u novom praznom objektu
    • Da li ima SVOJ property Name.hasOwnProperty() ne vraca inherited
    • name.instanceof Object da li je instanca
    • console.info(element) vraca prototip sa svim metodima
  4. Object.create metod

  5. Accessing object and values and editing it by declaring it with =

     console.log(objName.objKey);
     //or -->without '' if it is a number
     console.log(objName.['objKey']);
     //or by declaring a variable with keyName
     var a = 'keyName';
     console.log(objName.[a]);
     //edit object
     objName.keyName = newValue;
     //access function
     objName.funct(Arg);
  6. Usefull objects methods

       //this je trenutni objekat
       this.keyName;
       //example-> napravi ili edituj age key i daj mu vrednost 2018- godina rodjenja tog objekat
       this.age =  2018- this.birthYear;

Loops

  1. For Loop

     for(initialCounterValue = x; condition; counterUpdate){
       //what to do if all 3 conditions went well
     }
  2. While Loop

     var counter = innitialValue;
     while(condition){
       //do while condition is true
       counterUpdate;
     }
  3. Continue and Break Statements

     continue //-> kada se stavi pored if statementa za neki uslov,ako naidje na slucaj kada nije ispostovan uslov samo ce da nastavi dalje, nece nista raditi sa tim slucajem
     break //-> kada se stavi pored if statementa za neki uslov,ako naidje na slucaj kada nije ispostovan uslov sne nastavlja dalje nego prekida izvrsavanje

Hoisting Scope and This

  1. When we declare function we can use them even before they are declared in code because it is hoisted in JS.

     funcName(arg);
     function funcName(arg){
       //what it does
     }
  2. When we try to use variable before its declaration in code it will be undefined, but it will exist. That is beacause on the execution start code scans all variables and sets them to undefined.

  3. Scoping works from bottom to top. Not in opposite direction. Local definitions are never accessible to global ones if they are not returned from functions.

  4. Where does this point

    • regular function call -> on global object
    • method call -> object that is calling the method, method is function inside an Object
    • in function call -> on global object -in case of browser -Window
Clone this wiki locally