Java Script
Java Script
Variables
Javascript is a dynamically typed language. It means you don't need to worry about datatype
when creating variables. They are automatically resolved at runtime.
var myVariable1 = 5;
let myVariable2 = 5;
const myVariable1 = 5;
The last in pretty obvious. It just creates a constant. Once declared it cannot be changed.
The difference between first two is that let has a block scope and var doesn't.
// var
for(var i = 0; i < 5; ++i){
console.log(i);
}
console.log(i); // This will print 5
// let
for(let j = 0; j < 5; ++j){
console.log(j);
}
console.log(j); // Error. variable declared using `let` cannot be referenced
outside loop
Another difference between them is is that variables declared using var can be redeclared.
// var
var myVariable = 5;
var myVariable = 10; // Fine
// let
let myVariable2 = 5;
let myVariable2 = 10; // Error
You can introduce some bugs in your program using var . So most of the time we'll be using let
and const as they are safer than var .
Note: Try this is node.js. console in chrome doesn't throw error when redeclaring variables using
let keyword.
There is one more way is declaing variables in JavaScript and it is not a recommended one. We
can simple write variable's name without using any of the above keywords.
x = 5;
console.log(x);
function myFunc(){
x = 1;
let y = 2;
var z = 3;
const w = 4;
}
myFunc();
console.log(x); // Prints 1
console.log(y); // Error
console.log(z); // Error
console.log(w); // Error
Declaring variables like this actually adds it a global object named window (in browsers) and
global (in Node.js). So you can also access it using global.x .
x = 5;
console.log(global.x); // console.log(window.x) in browsers
Datatypes
There are following data types available in JavaScript
// 1. Number => This includes all integers and floating point numbers
let num1 = 5;
let num2 = 10.45;
// 2. Boolean
let boolVar1 = true;
let boolVar2 = false
// 3. String
let str1 = "This is a string";
let str2 = 'This is another string'; // Both " " and ' ' are acceptable for
strings.
// 4. Array
let arr1 = [1, 2, 3, 4, 5];
let arr2 = ["str1", "str2", "str3"];
// 5. Objects
let person = {
name: "Dev",
age: 25,
occupation: "Programmer"
};
Note: Semicolons are optional in JavaScript unless you don't write more than one statement per
line
let x = 5; // fine
let y = 2 // fine
var a;
console.log(a);
// undefined
var b = null;
console.log(b);
// null
Variable Hoisting
In Javascript all variable and function declarations float to the the top of the program.
console.log(x);
var x = 5;
Above line prints undefined as as declaration of variable x floats to top. Above code is
equivalent to.
var x;
console.log(x);
x = 5;
Note: This works only for var and not for let .
Printing
You might have already seen console.log in above examples. This functions simply prints to
screen.
let x = 2;
console.log(x);
let person = {
name: "Dev",
age: 25,
occupation: "Programmer"
};
Note that we have use backticks (`) instead of quote (') in above example.
Control Flow
Conditional Statements
They are exactly same as C/C++
Comparison Operators
The comparison operators are usual with one major difference.
x < y
x > y
x <= y
x >= y
x == y
x === y // Yes we have ===
x != y
x !== y
x == y checks if two values are same after doing implicit conversion if required.
On the other hand x === y checks if two values are same and their type is also same.
This will be clear in following example.
There are various pitfalls in JavaScript when using these comparison operators. Check this and
this.
switch(myChar){
case 'a': console.log('This is A');
break;
case 'b': console.log('This is B');
break;
case 'c': console.log('This is C');
break;
// 2. for..in loop
for(let i in animals){ // This loops over all indices of array
console.log(animals[i]);
}
// 3. for..of loop
for(let animal of animals){ // This loops over all elements of array
console.log(animal);
}
// 4. while loop
let i = 0;
while(i < animals.length){
console.log(animals[i]);
++i;
}
// 5. do while loop
let j = 0
do {
console.log(animals[j]);
++j;
} while(j < animals.length);
Functions
There are two ways of declaring functions in JavaScript
// Normal way
function sayName1(name){
console.log('Hello ' + name);
}
sayName1('Dev');
If our function has only one statement which returns something we can also drop { }
// ver 1
const square = x => {
return x * x;
}
// ver 2
const square = x => x * x;
let sq = square(2);
let x = 5;
x = increment(x, 2); // x = x + 2;
x = increment(x); // x = x + 1;
Both are equally good with one major difference i.e. arrow function doesn't bind to this . This
difference isn't important for this course. But if you are interested you can read more here.
Arrays
JavaScript Arrays are dynamically resized. This means we don't have to specify the size when
declaring.
Unlike most other languages, JavaScript does throw out of bounds error when we try to access
element at index greater than or equal to length of array.
Array Methods
There are tons of methods available with array. We'll a few of them here.
// length of array
console.log(fruits.length);
// Concatenation
let moreFruits = ['grapes', 'strawberry'];
fruits = fruits.concat(moreFruits);
console.log(fruits);
// Slicing
let slice = fruits.slice(1, 5); // 1 is inclusive and 5 is exclusive
console.log(slice); // prints ['orange', 'mango', 'pomegranate',
'grapes'];
console.log(fruits.slice(3)) // prints ['pomegranate', 'grapes',
'strawberry'];
// Sorting
let numbers = [5, 7, 1, 2, 8];
numbers.sort();
console.log(numbers); // prints [1, 2, 5, 7, 8];
// Reverse
numbers.reverse();
console.log(numbers); // prints [8, 7, 5, 2, 1];
There are a lot more methods available for arrays. Check this if you want learn more about array
methods.
Objects
JavaScript objects are similar to dictionaries or hash tables in other programming languages
let person = {
name: 'Dev',
age: 25,
occupation: 'Programmer'
};
// Delete property
delete person['hairColor'];
console.log(person);
For values we can use anything a number, string, bool, array, other objects and even functions.
let person = {
name: 'Dev',
age: 25,
occupation: 'Programmer',
run: function(){
console.log('I am running');
},
hobbies: ['reading', 'listening music'],
otherData: {
hairColor: 'black',
height: 178,
weight: 67
}
};
person.run();
Destructuring
Destructuring allows us to assign the properties of an array or object to variables This is similar to
tuple unpacking in python.
// Arrays
let fruits = ['banana', 'orange', 'mango'];
let fruit1 = arr[0];
let fruit2 = arr[1];
let fruit3 = arr[2];
// trailing capture
let [head, ...tail] = arr;
console.log(head, tail); // prints 1 [4, 5, 7, 1, 6]
let person = {
name: 'Dev',
age: 25,
occupation: 'Programmer'
};
If you want to change the name of variables you can do something like following.
We can use default value here is that member is missing in given object
let header = {
ip: '192.0.2.1',
port: 443
};
let data = {
isValid: true,
length: 5,
arr: ['Hi', 'There', 'This', 'Is', 'Dummy', 'Data']
};
Destructuring is useful when you want access only certain parts of passed objects to a function.
let data = {
isValid: true,
length: 5,
arr: ['Hi', 'There', 'This', 'Is', 'Dummy', 'Data']
};
analyseData(data);