JavaScript Notes — 1
Variables, Array, Object, Strings
Notes have been prepared by doing the course of Full Stack Web Development in Node.js by Arnav Gupta, Coding Blocks.
Plus, some additional information have been added.
Attaching external JS file to our html file:
<html>
<head>
</head>
<body>
<!-- content -->
<script src = './file.js'>
</script>
</body>
</html>Ways to declare a variable
x ; let x ; const x ; var x ;
Variables defined outside function have Global scope (Except in window object, in which variables defined outside are not valid).
let or const have block scope, i.e. accessible inside current braces and inside all the inner nested braces.
Note: Can be re-defined in inner scopes but if in any inner scope, value of outer scope has been used, then redifinition is not possible.
var has function scope, and not global. Can be re-defined anywhere.
Example to understand that scope of
varis function and not global:
function print (){
var x = 10;
console.log(x);
}
print(); // 10
console.log(x); // errorExample to understand how redefining works in block scope i.e. in
letandconst
let/const x = 10; // Scope A
function alpha (){ // Scope B
let/const x = 20; // - - > redefinition possible
if(true){ // Scope C
let x = 30;
}
}In Scope B of the above code, if we do not redefine x and directly try to access x it will give 10 (taken from outer Scope A) and now if we try to redefine x it will give error.
In case of
varinside function hoisting takes place for its definition.
Try to guess output of the following example:
var x = 10;
function func(){
console.log(x);
var x = 20;
console.log(x);
}
func();Output:
undefined
20Explanation:
The above code gets converted to:
var x = 10;
function func(){
var x;
console.log(x);
x = 20;
console.log(x);
}
func();If we haven’t given in anything at return of a function, its return type is said to be undefined.
Hoisting
Defn of declared functions and declared classes go at the top, before all statements. Thus while writing code, we can give the code of calling a function before its definition. And inside a fn, hoisting takes place for variables defined using var as well, as we saw above.
These are called Declared Functions (Hoisted)
function func(){
// . . .
}These are called Expressed Functions (Not hoisted)
var x = function () {
// . . .
}Example:
func_a(); // this will be valid
func_b(); // this wont be
function func_a(){
// . . .
}
var func_b = function(){
// . . .
}As we saw that inside function definition, hoisting doesn’t take place for const and let.
But what about outside function, i.e. in global context?
How does hoisting take place for them?
Turns out that in global context, hoisting for let and const takes place in the Temporal Dead Zone (TDZ). i.e. even though the declarations go at the top, accessing them before initialization will give Reference Error.
console.log(x);
let x = 50;Behaves like this:
let x; // This is Temporal Dead Zone (TDZ)
console.log(x); // Gives Reference Error
x=50;The above code is different from:
var x;
console.log(x); // gives undefined
x=50;
Because, here, x wasn’t declared in TDZ.
Arrays
Can contain different data types as well.
let arr = ["Apple", "Mango", "Guava"];
console.log ( arr["length"] ); // 3
console.log ( arr.length ); // 3Iterating over elems of array:
for(let i=0; i<=2; i++){
console.log( arr[i] );
}Array functions:
let arr = ["Apple", "Mango", "Guava"];
arr.indexOf("Mango"); // 1
arr.push("Grapes"); // add elem to end
arr.pop(); // remove elem from end and returns that elem
arr.shift(); // remove elem from front and returns that elem
arr.unshift("Kiwi"); // add elem to front
arr.reverse(); // reverses the order of elems in the same arraySlicing an array is non-destructive: New array is returned and original array is not affected.
let arr2 = arr.slice(4); // arr2 has elems from idx [4, end]
let arr2 = arr.slice(4, 6); // arr2 has elems from idx [4, 6) = 4th, 5th S`p`licing is destructive. New array is returned and the original array is affected.
let arr2 = arr.splice(4); // arr2 has elems from idx [4, end]
// arr1 has elems from idx [0, 3]let arr2 = arr.splice(4, 2); // The second argument in splice denotes length (like in substr) , to be spliced. So, [4, 6] will be deleted from original array
arr.splice(4, 3, "p", "q", "r"); // Third and beyond argument in splice is used to replace one by oneSome other important functions for arrays:
let arr2 = arr.concat("donut", "eclair"); // Returns new array by adding new elems to the end. Original array is not affected. Non destructive
let arr2 = arr.map ( elem => `<li>elem</li>`); // Returns a new arr by modifying each elem of the existing arr. Non destructive
let str2 = arr.join('\n'); // Joins elems with the given symbl and returns a string
let str2 = arr.filter( (elem) => elem.length > 2 ); // Returns a new array, which contains elemenets which pass the given conditionOn an array, we can apply forEach() function. The function itself takes a function in argument (say function2), which is applied over each elem of the array. The function2 in definition takes two parameters, which are value and index of elems of current array.
Get Sriram’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
function func(x, y){
console.log(x, y);
}
let arr = [10, 20, 30, 40];
arr.forEach(func);Or, using anonymous function to define function at the place of calling itself:
let arr = [10, 20, 30, 40];
arr.forEach(function(x, y){
console.log(x, y);
});Or, using arrow function to define function at the place of calling itself:
let arr = [10, 20, 30, 40];
arr.forEach( (x, y) => {
console.log(x, y);
});All the above 3 blocks of code output the same thing:
10 0
20 1
30 2
40 3
for ( of ) for ( in )
for (let x of arr){
// iterates through values in array
}
for (let x in arr){
// iterates through indices in array. Trick: AUfbav Principle
// OF Value, Prop IN
}Objects
In JS, we can create objects without class.
Object = Collection of key-value pairs. Where key can only be string.
let obj = {
a: 100, // can also write - - > "a" : 100 ,
b: 'hello',
10: 200
} ;When the key is given as numeric or any non string like bool. It has different accessing style.
obj.a; // works. // outputs 100
obj.10; // doesnt work
obj [' 10 '] ; // works
obj [' a '] ; // also works. Similarly, obj [ ' true ' ] ; // would have worked for bool keyKeys can contain values of different data types.
var bird = {
x: 100,
y: 20,
color: "blue",
eggs: [81, 82, 83, 84];
};
bird.color= "red";
console.log(bird.x); // 100
console.log(bird.color); // red
console.log(bird.eggs.length); // 4
bird.eggs.forEach((x, y)=>{ // - - > x: value y: index
console.log(x, y);
});
/*
Outputs:
81 0
82 1
83 2
84 3
*/Note: Keys can even contain functions or other objects also. But properties inside object are not local variables.
Example:
var bird= {
x: 10,
y: [20, 30, 40],
z: function(){
console.log("Generated by a function");
/*
We can't access x or y directly.
We will have to use 'this' keyword.
*/
// console.log(x); // Doesn't work
console.log(this.x); // Works
}
};
bird.z(); // Outputs: Generated by a functionWays of creating object:
- Object literal
var apple = {
taste: "sweet",
color: "green",
};2. Function declaration (hoisted) | this , new keywords are used.
function Fruit(taste, color){
// declaring the properties of object as well as
// assigning values to it
this.taste = taste;
this.color = color;
}
let mango = new Fruit("sweet", "yellow");
let orange = new Fruit("sour", "orange");
apple; // {taste: "sweet", color: "red"}
orange.taste; // "sour"3. Function expression (not hoisted) | this , new keywords are used.
let f = function (a, b){
this.height = a;
this.weight = b;
}
let a = new f (190, 100);Note: It’s not possible to create object in JS using arrow functions. Because arrow functions don’t have a this keyword of their own. When we use this inside arrow functions, it refers to the scope where the arrow function was defined.
4. Class declaration (hoisted) | constructor , this , new keywords are used.
class FruitClass{
constructor(taste, color){
this.color = color;
this.taste = taste;
}
};
let kiwi = new FuitClass ("sour", "green");5. Class expression (hot hoisted) | constructor , this , new keywords are used.
let FruitClass2 = class {
constructor(taste, color){
this.color = color;
this.taste = taste;
}
};
let kiwi2 = new FruitClass2 ("sour", "dark green");Strings
There are three ways to create a string: single quotes, double quotes and backticks.
let name = 'Raghav'; // Single quotes
let newname = `My name is ${name}`; // Backticks can also be used to create String
console.log(newname); // My name is RaghavWe can write long string in single quotes using \
On output those \ will not be printed and there will be no newline.
Example:
let x = 'This is going to be a \
very long \
string';
console.log(x);
// Output: This is going to be a very long stringIf inside a quote style, we use another quote style then we need not escape that. But if we use the same quote style inside the given quote style, we will need to escape that.
Example:
let s = ' " wow " ' ; // No need to escape double quotes inside single quotes
let s = " ' wow ' " ; // No need to escape single quotes inside double quotes
let s = ' \' wow \' ' ; // Required to escape single quotes inside single quotes
let s = " \" wow \" " ; // Required to escape double quotes inside double quotes
let s = ` "wow" ` ;
let s = ` 'wow' ` ;To output newline in strings defined using single and double quotes:
let s = " string in \n multiple \n lines " ;To provide newline when using backtick :
let s = ` string in
multiple
lines ` ;It gets printed exactly as it has been written. Thats why backticks are called string literals.
let name = "Raghav" ;
let a = "My name is " + name ; // concatenation in double quotes // same for single quotes
let b = `My name is ${name}` ; // concatenation in backticks
// ${ } , can also have mathematical operations
let c = ` So, 10 plus 2 is : ${ 10 + 2 } ` ;String functions:
let x = "Raghav is Raghav";
x.length ; // 16
x.indexOf('ghav'); // First occurence - - > 2
x.indexOf('ghav', 4); // Start searching from index 4 // - - > 12
x.lastIndexOf('ghav'); // Last occurrence - - > 12
x.slice(2, 3); // [ 2, 3 )
// splice is not suppported on string
x.substring(2, 3); // [2, 3)
x.slice(-6, -4); // [-6, -4) // Last char is denoted as -1
// But, x.slice(5, 3); or, x.slice(-4, -6); both dont work. We can't slice in reverse direction
// i.e. we can only slice from less value to larger value
x.substr(3, 4); // second param is length // starting from index 3. length 4. // [3, 6]
x.substr(-6, 4); // [-6, including -6 idx till 4 elements to the right]
x.split("<delim>"); // Returns a new array of substrings separated by given delimitter
// Non destructivelet x = "Hi-how-are-you";
let y= x.split('-');
console.log(y);
// Outputs: [ 'Hi', 'how', 'are', 'you' ]





