Variable and Parameter

KeywordScopeIsMutable

var

function

yes

let

block

yes

const

block

no

if (true) {
    let a = 40;
    console.log(a); // 40
}
console.log(a);     // undefined.
let a = 50; let b = 100;
if (true) {
    let a = 60;
    var c = 10;
    console.log(a/c);         // 6
    console.log(b/c);         // 10
}
console.log(c);                 // 10
console.log(a);                 // 50

Destructuring

Destructuring Arrays

let x = 3;
let y = 2;

[x,y] = [y,x];

//x=2
//x=3 

Destructuring Objects

let test = {
    firstName: "John",
    lastName: "Doe"
};

let {first, last} = test;

//first = "John"
//last = "Doe"

default parameters

var doWork = function(name = "John"){
    return name;
};

var result = doWork();
//var result = doWork(undefined);

//result = "John"

//var result = doWork("Scott");
//result = "Scott"

Rest Parameter (is like varargs)

  • Rest parameter allows the functions to accept an indefinite number of arguments as as array.

  • Rest parameter should appear after any regular parameters.

let doWork = function(name, ...numbers){    //rest parameter
}
function greet(...names){
    names.forEach(name => console.log('Hi, ' + name));
}

greet('Rose', 'Mary', 'Marlo')
//Hi, Rose
//Hi, Mary
//Hi, Marlo
function greet(message, ...names){
    console.log(message);
    names.forEach(name => console.log('Hi, ' + name));
}

greet('Hello, World!', 'Rose', 'Mary', 'Marlo')
//Hello, World!
//Hi, Rose
//Hi, Mary
//Hi, Marlo

Spread Parameter

  • Spread parameter is the exact opposite of how Rest parameter works.

  • It allows a function to take an array as as argument and then spread out its elements so that they can be assigned to individual parameters.

let doWork = function(x,y,z){
    return x+y+z;
};

var result = doWork(...[1,2,3])    //spread parameter

// x=1  y=2  z=3    result = 6

var a = [4,5,6]
var b = [1,2,3,...a,7,8,9]        //spread parameter

//b = [1,2,3,4,5,6,7,8,9]
function greet(person1, person2){
    console.log('Hi, ' + person1 + ' and ' + person2);    //Hi, John and Jane
}

let names = ['John', 'Jane');
greet(...names);                // spread parameter

Template Literals

let username = "john";
let url = `https:\\github.com\${username}`;

//url = https:\\github.com/john-***********/*-///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
console.log(a);    // error
var a;             // undefined
  • JavaScript always hoists the declaration of any variable at the top so even if in code it appears to be after calling the variable it won't give an error.

Last updated