Table of contents
This is the second part of JavaScript Fundamentals. Before please go through JavaScript Fundamentals Part - 1 to get good understanding.
Strict Mode
The purpose of use strict
is to indicate that the code should be executed in "strict mode".
With strict mode, you can not, for example, use undeclared variables.
Example
let isLogin = false;
islogin = true;
if(isLogin){
console.log("Show Logout Button");
}
In the above example we are supposed to get Show Logout Button but it shows nothing in the console. I have intentionally misspelled islogin which is not declared. Still, it does not show any error in the console.
So to avoid this kind of bug we can use strict mode
. Now try running the below code and see if it gives an error in the console.
'use strict'
let isLogin = false;
islogin = true;
if(isLogin){
console.log("Show Logout Button");
}
Also, when we try using reserve keywords without using strict mode
we don't get any warning or error. Run the below code on your local machine and see if it gives an error.
let private = 2122; // private is reserve keyword in JavaScript
But when we use strict mode we will get a warning in the console that we are using the reserved keyword as a variable.
'use strict'
let private = 2122; // private is reserve keyword in JavaScript
It is always preferred to use strict mode when building an app in JavaScript
Function
A function is a block of code that performs a particular task.
SYNTAX
function function_name(parameter-1, parameter-2){
// Function code
}
Let's understand functions by taking more examples.
//function
function greet(){
console.log("Good Morning");
}
greet(); // function call
When we call function then and then only it runs. In the above example when we call the function it prints Good Morning
in the browser's console.
Function return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
Functions often compute a return value.
// function
function greet(greeting){
const msg= `Good ${greeting}`;
return msg;
}
greet("Morning"); // This will print nothing
console.log(greet("Morning")); // This will print message what function returns.
Why Functions?
You can reuse code - Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
Function Expressions
In JavaScript, functions can also be defined as expressions.
EXAMPLE
const fun = function(name){
const msg = `Good Morning, ${name}`;
console.log(msg);
}
// Function Call
fun("JavaScript");
Arrow Function
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
There are differences between arrow functions and traditional functions, as well as some limitations. We will discuss this in future articles.
EXAMPLE
const fun = (name) =>{
return `Good Morning, ${name}`;
}
console.log(fun("JavaScript"));
Function calling other functions
We can call functions from other functions. It would be easy if we do it practically.
const fun= (fname , lname) =>{
return fname + " " +lname;
}
const greet= (fname, lname, greeting) =>{
const fullName = fun(fname, lname);
const msg = `${greeting} I am {fullName}`;
return msg;
}
//Function call
console.log(greet("Jimmy", "Wagner", "hello"));
Introduction to Array
If we want to create a list of students we have to create a new variable for a new student. This is where arrays come into the picture to make our work easy. We can declare one variable and store all student names in an array.
In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics.
JavaScript arrays are zero-indexed. The first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.
JavaScript array can have multiple datatype arrays.
E.g - const arr = [1,2,3,"kedar",6.1];
SYNTAX
let arr = [1,2,3,4,5];
let arr2 = new Array(1,2,3,4,5);
Accessing array elements and array length
Array in JavaScript start from 0 till n-1.
let arr = [75,35,87,09,67];
// 0th element = 75
// 1st element = 35
// 2nd element = 87
// Accessing array elements
console.log(arr[0]);
console.log(arr[1]);
// length of array
console.log(arr.length)
//last element of array
console.log(arr[arr.length-1])
Array Methods (Operations)
Array methods or operation are built-in functions that JavaScript provide to perform an operation on the array.
push: add an element in the array at the end.
pop: remove the last element from an array.
indexOf: return an index of element if it exists in the array.
includes: return true if the array consists given element in the array.
EXAMPLE
const friends= ["bob","alex","kevin","max"];
friends.push("Alice"); // add element in array
friends.pop(); // remove last element in array
console.log(friends.included(101)); // return false because 101 doesn't exist in array
console.log(friends.included("bob")); // return true because bob exists in array
Introduction to object
The object is a variable in which there are multiple keys and value pairs.
// Object declaration
const obj = {
name: "JavaScript",
age: 30,
}
It is a common practice to declare objects with the const keyword.
Accessing object values
We can access object values using 2 menthods.
- using dot(.)
- using bracket notation ([])
- Using dot(.)
We can access object using dot(.).
EXAMPLE
const obj = {
name: "JavaScript",
age: 30,
}
console.log(obj.name)
- Using bracket notation([])
We can access object using dot(.).
EXAMPLE
const obj = {
name: "JavaScript",
age: 30,
}
console.log(obj["name"])
Object Method
We have learned how to create objects. Now we will learn to create methods for objects.
In objects, we can create functions that can be accessed using dot(.) notation along with the object name.
EXAMPLE
const obj = {
name: "Alex",
birthYear: 1998,
// object method
calcAge: function(){
return 2023 - this.birthYear;
}
}
console.log(obj.calcAge()); // Calling object method
Consider this
keyword as the object itself we have a detailed article on this
keyword.
Loops
Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over and over again, each time with a different value.
JavaScript supports different kinds of loops:
- for - loops through a block of code a number of times
- while - loops through a block of code while a specified condition is true
- do/while - also loops through a block of code while a specified condition is true
The For Loop
The for statement creates a loop with 3 optional expressions:
EXAMPLE
for(let i=0;i<10;i++){
console.log(i);
}
In the above code i=0 then loop check if i < 10 if true control goes inside and perform an action which is inside of braces. In this case, it will print the value of i. This keeps repeating until i<10 condition becomes false.
The While Loop
The while loop loops through a block of code as long as a specified condition is true.
If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
EXAMPLE
while (i < 10) {
console.log(i);
i++;
}
The Do While Loop
The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
The example below uses a do while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.
EXAMPLE
do {
console.log(i);
i++;
}
while (i < 10);
Looping through array
Using for / while loop we can iterate through array.
- Using for loop
let arr = [87,76,65,54,89];
for(let i=0;i<arr.length;i++){
console.log(arr[i]);
}
- Using while loop
let arr = [87,76,65,54,89];
let i=0;
while(i<arr.length){
console.log(arr[i]);
i++;
}