blog bg

September 23, 2023

JavaScript: Fundamentals

Share what you learn in this blog to prepare for your interview, create your forever-free profile now, and explore how to monetize your valuable knowledge.

 

VALUES AND VARIABLES(learn more)

A Value is basically a piece of data, so basically a piece of information and we store them into variables. So that we can reuse them over and over again. For example,

const text = "some text";

text is actually name of the variable and assign a value "some text", this is called declaring a variable

Note:- In JavaScript, whenever we need to output something from our code, we always to console.log

const text = "some text";
console.log(text); //output -> some text

However, JavaScript follows some rules when naming variables,

  1. Name must start with a letter, and underscore(_) and or a dollar sign($)
  2. Name cannot contain spaces
  3. Name cannot be the same as reserved keywords like if, const, let..
  4. Name can only contain numbers, letters, underscores and the dollar sign
  5. By convention, name  should not start with an uppercase
  6. By convention, constant variable can be written in all uppercases
  7. By convention, name is written in camelCase
let firstName = "some name" //valid
let first_name = "some name" //valid
let 1stName = "some name" //invalid - rule 1
let first&Name = "some name" //invalid - rule 1
let function = "some name" //invalid - rule 3
let FirstName = "some name"// valid not never do that it should be firstName - rule 5
let PI = 3.14 //valid rule - 6
 
Let,Const and Var
In JavaScript, there are three different ways of declaring variables. let and const are modern JavaScript and were introduced in ES6. While the var keyword is the old way of declaring variables. Lets have a look how differ and which one to use in  which situations,
 
We use the LET keyword to declare variables that can change later. For example,
let year = 2023
console.log(year); // 2023
year = true
console.log(year); // true
year = "current"
console.log(year); // current
We use the CONST keyword to declare variable that are not supposed to change at any point in the future. hence, the value in const variable cannot be changed 
const birthYear = 2000
birthYear = 2001 // it will throw an error

const birthYear; // it will also throw an error, when using const we need
basically an initial value
VAR keyword is basically the old way of defining variables prior to ES6 and at first sight, it works the same as Let.
var firstName;
firstName = "first name"
console.log(firstName); // first name
 

DATA TYPES(learn more)

Generally, values can have different types, depending on what type of data we want, In JavaScript every value can be either an OBJECT or a PRIMITIVE value. Lets focus on the primitive value, there are 7 types of primitive data, which are,

  1. Number: Integers, decimals
  2. String: Sequence of characters and put them in quotes
  3. Boolean: Either true or false
  4. Undefined: variable is defined but value is not assigned yet
  5. Null: empty value
  6. Symbol: value that is unique and can not be changed
  7. BigInt : large integers
let year = 2023
let isChecked = true
let month;
let day = "today is monday";
console.log(typeof isChecked); // boolean
console.log(typeof year); // number
console.log(typeof month); // undefined
console.log(typeof day); // string
Note: In JavaScript, we don't need to manually define the datatype of the value stored in a variable, datatypes are determined automatically 

 
BASIC OPERATORS(learn more)
An operator basically allow us to transform values or combine multiple values. There are many categories of operators like mathematical operators, comparison operators and more. let's have a look some of these.
 
Arithmetic Operators
Addition(+), Subtraction(-), Multiplication(*), Exponentiation(**), Division(/), Modulus/Remainder(%), Increment(++) and Decrement(--)

let num = 4
console.log(num ** 3); //64
console.log("first "+ "name"); //first name
console.log(num ** 3); //64
num += 10;
console.log(num); //14
num *= 10;
console.log(num); //140
num++
console.log(num); //141
num--
console.log(num); //140
 
Comparison Operators
equal to(==), equal value and type(===),not equal(!=), not equal value or not equal type(!==), greater than(>), less than(<), greater than or equal to(>=), less than or equal to(<=),ternary operator(?)
 
console.log(curYear == 2022);//true
console.log(curYear == '2022');//true
console.log(curYear == 2022);//true
console.log(curYear === '2022');//false
console.log(curYear == 2022 ? "matching" : "not matching");//"matching"
 
Operator Precedence
this will describer the order in which operations are performed in an arithmetic expression. Multiplication(*) and division(/) have higher precedence than addition()+ and subtraction(-)
 
Logical Operator
logical and(&&), logical or(||), logical not(!)
let age = 20
let A= age >= 20 //true
let B = age < 10 //fasle
console.log(!A); //false
console.log(A && B);//false
console.log(A || B);//true
console.log(A && !B);//true
 
 
TYPE CONVERSION
Three types of functions we used in JavaScript for converting datatypes.
  • Number(): Used when we convert the given input value to the number type. However, if we want to convert the given input into an int or float type, then we have to use parseInt() to convert it into an int type and the parseFloat() to convert it into a float type
const myAge = "20";
console.log(Number(myAge) + 18); //38
console.log(Number("String")); //NaN
console.log("23" - "10" - 3); //10 - minus operator actually triggers the opposite conversion
console.log("23" / "10"); //2.3
  • String(): used when we want to convert the given input value to the string type. If we pass any character, number, etc in this function then it will be converted into a String
console.log(String(123))      // returns a string from a number literal 123
console.log(String(100 + 23))  // returns a string from a number from an expression
console.log(String(true)) // returns a string from Boolean
  • Boolean(): used when we need to convert the given input value to Boolean type
console.log(Boolean(0)); //false
console.log(Boolean('name')); //true
console.log(Boolean({})); //true
console.log(Boolean(undefined)); //false

 
TEMPLATE LITERALS(learn more)
consider following variables,
const firstName = "John";
const lastName = "ABraham";
const birthYear = 1991;
const currentYear = 2023;
Generally to contaminate strings, we can use plus(+) signs. for example,
const personDetails = "My Name is "+ firstName + " "+lastName+", a "+
                        (currentYear - birthYear)+ " years old"
console.log(personDetails);//My Name is John ABraham, a 32 years old

In ES6, a much better tool is introduced to handle this kind of complex string called Template literals/strings. it uses backtick(`) rather than quotes to define string. So with Template literals, we can write above string in normal way and then basically insert the variables directly into the string and then they will simply be replaced. for example,

const personDetails = `My Name is ${firstName} ${lastName}, 
                        a ${(currentYear - birthYear)} years old`;
console.log(personDetails);//My Name is John ABraham, a 32 years old
 
 
STRICT MODE(learn more)
It is a special mode that we can activate in JavaScript which makes it easier for us to write a secure JavaScript code. To activate strict, write "use strict" at the beginning of the script that's it. basically this has to be the very first statement in the script. Also, we can activate strict mode, only for a specific function or a specific block as well.
'use strict';
/*
write your javascript code bellow strict mode
*/
Strict mode will allow us to avoid accidental errors. So basically it helps us to introduce the bugs into our code. In certain situations, strict mode will create visible errors for us in which without strict mode JavaScript will simply failed silently.
 
for example,
'use strict';
let checked = false;
const valid = true

if(valid)  check = true;//we forgot to put 'ed' here, without strict mode,
JS will not show any error. since we use strict mode, JS will show the error
if(checked) console.log('it is valid');
 
 
FUNCTIONS(learn more)
functions are the fundamental building block of JavaScript applications are functions. They are the one on the most essential concepts in the language. a function is a piece of code that we can reuse over and over again our code. So its a little bit like a variable but for whole chunks of code

Function Declarations
examples,
function test(){
    console.log("we are inside a function");
}
//to calling/running/invoking the function
test(); // it will print "we are inside a function"
 
Pass parameters to Function
function addNumbers(num1, num2){
          return num1+num2
}
let sum1 = addNumbers(1,3);// 1,3 will get passed into the function as parameters
console.log(sum1);// 4
let sum2 = addNumbers(10,5);
console.log(sum2);//15
 
Function Expression 
functions shown in above examples are called function declarations because we simple use the function keyword to declare a function a bit like we declare a variable. In function expression, instead of writing a function with name, we simply write function without a name and then we still define the parameter, we still define the function body and store it in variable and this will then be the function. For example,
const addNumbers2 = function (num1, num2){
    return num1+num2
}
let sum3 = addNumbers2(10,25)
console.log(sum3);
 
Function Declarations vs Function Expression 
we can actually call function declarations before they are defined in the code, however, we can not access the function before initialization.For example,
let sum = addNumbers(1,3);
console.log(sum); //it will work as it is function declarations
function addNumbers(num1, num2){
    return num1+num2
}
let sum3 = addNumbers2(10,25)
console.log(sum3);//it will throw an error
const addNumbers2 = function (num1, num2){
    return num1+num2
}
 
Arrow Functions
This is a type of function that was added to JavaScript ES6. Arrow function is simply a special form of function expression that is shorter and therefore faster to write,

//arrow function
//type 1
const addNumbersArrowOne = (num1, num2) => {
    return num1+num2
}
let sum2 = addNumbersArrowOne(1,3);
console.log(sum2);//4
//type 2
const addNumbersArrowTwo = (num1, num2) =>  num1+num2
let sum3 = addNumbersArrowTwo(2,3);
console.log(sum3);//5

 

Calling a function from other function
function numberTwo(num){
    return num/2
}
function addNumbers(num1, num2){
    return num1+numberTwo(num2)
}
const sum = addNumbers(5,10);
console.log(sum);
 
 
ARRAYS(learn more)
An Array is a data stricture and it can hold more than one value, for example,
const num1 = 10
const num2 = 12
const num3 = 14
As you can see, we have three numbers so we created 3 variables, imagine if we have 20 numbers then we will have to create 20 variables, that does not sound good instead, it would be great if we keep them together in one place, and we called that place as Array. It's like a big container into which we can throw variables and then later reference them.
 
we can define array in two ways, for example,
//type 1
const numbers = [num1,num2,num3];

//type2
const numbersArray = new Array(num1,num2,num3);
console.log(numbers);//[10,12,14]
console.log(numbersArray);//[10,12,14]
 
Access array elements
we can access the elements inside array based on their index. In array index starts from 0.
for example,
const numbers = [10,13,16];
console.log(numbers[0]);//10
console.log(numbers[1]);//13
console.log(numbers[2]);//16

//length of the array
console.log(numbers.length); //3

//replace an element in array
numbers[2] = 20;
console.log(numbers); //[10,13,20]
 
Basic Array Operations
consider the following array
const numbers = [10,13,16];
  • Add element at the end of the array
numbers.push(19);
console.log(numbers);//[10, 13, 16, 19]
  • Add element at the beginning of the array
numbers.unshift(8);
console.log(numbers);//[8, 10, 13, 16]
  • remove the last element from the array
numbers.pop();
console.log(numbers);//[10, 13]
  • remove the first element from the array
numbers.shift();
console.log(numbers);//[13,16]
  • find the position of specific element in array
const index = numbers.indexOf(13);
console.log(index);//1
  • check if the array has an element
console.log(numbers.includes(13));//true
console.log(numbers.includes(15));//false
  • remove element from array at specific position
numbers.splice(1,1);
console.log(numbers);//[10,16]


 

OBJECTS(learn more)

Objects are one of the data structures in JavaScript. lets consider following array,
const person = ['person name',30,'web developer']
By seeing the array, we know that first element of the array is first name. second element could be called age and other one could be called job. However, in array there is no way of giving these elements a name so, we cant reference them by name but only by their index. To solve the issue, we have another data structure Objects

Defining object
const person = {
    name:"john",
    age:41,
    job:'retailer',
    hobbies:['music','movies','golf']
}
 
Access Objects
//accesss the object
//type 1
console.log(person.name);//"john"
console.log(person.job);//"retailer"
//type 2
console.log(person['name']);//"john"
console.log(person['job']);//"retailer"
 
Object Methods
Any function that is attached to an object is called a method.  we will use function expression to create method inside object
for example,
const person = {
    name:"john",
    age:41,
    job:'retailer',
    hobbies:['music','movies','golf'],
    married:true,
    birthYear:function(age){
        return 2023 - age
    }
}

console.log(person.birthYear(41));//1982
from above example we pass the age into the birthyear function which then will give year. So what if we could actually access this age property directly from the object?. JavaScript gives us access to a special variable called this, by using this variable we can directly read the age directly from this object itself without having to pass it in as a parameter to the function.
 
for example,
//type 1
const person = {
    name:"john",
    age:41,
    job:'retailer',
    hobbies:['music','movies','golf'],
    married:true,
    birthYear:function(){
        return 2023 - this.age
    }
}
console.log(person.birthYear());//1982
//type 2
const person = {
    name:"john",
    age:41,
    job:'retailer',
    hobbies:['music','movies','golf'],
    married:true,
    birthYear:function(){
        this.bornYear = 2023 - this.age;
        return this.bornYear
    }
}
person.birthYear();
console.log(person.bornYear);//1982
 
 
FOR LOOP(learn more)
 
Loop Array
const numbers = [10,11,12,14,15];
for(let i = 0; i < numbers.length;i++){
    console.log(numbers[i]);
}
 
Continue and Break
With continue, we can exit the current iteration of the loop. for example, we have an array which contains both string and numbers. however we wanted to print elements to the array that are string. In that case, when we loop the array and if the current iteration is number then we stop the current iteration and move to next loop iteration. For example,
const array = [10,"one",11,"two",12,14,15];
let string = [];
for(let i = 0; i < array.length;i++){
    if(typeof array[i] == 'number'){
        continue;
    }
    string.push(array[i]);
}
console.log(string);//['one', 'two']
 
With break, we terminate the whole loop . So not just the current iteration. for example we have an array of numbers and look for a specific number. if the number is found terminate the loop and print that number. For example,
const numbers = [10,11,12,14,15,16]
let num;
let iteration = 0
for(let i = 0; i < numbers.length;i++){
    iteration++;
    if(numbers[i] === 12 ){
        num = numbers[i];
        break;
    }
   
}
console.log(num);
console.log('total iteration : '+iteration);//total iteration : 3
 
WHILE LOOP(learn more)
In while loop, we will specify a condition and while continue the loop until the condition is true. for example, we want to keep the loop running while repetitions is less or equal 10. For example,
let rep = 1;
while(rep <= 10){
    console.log(`rep ${rep}`);
    rep++
}
 
IF/ELSE STATEMENT(learn more)
It will execute a statement if a specified condition is true. Otherwise, else clause will be executed. for example,
    let day = 'monday';
    if(day = 'monday'){
      console.log('first day of the week');
    }else if(day = 'monday'){
      console.log('second day of the week');
    }else if(day = 'monday'){
      console.log('third day of the week');
    }else{
      console.log('not a valid day');
    }
    //OUTPUT - first day of the week
From the above example, execution starts from the if clause and it goes until the match found. if found then it will stop the execution. if we have multiple condition then we will have to write them in else if clause. else clause will be executed if there is not match found.
 

 

TENARY OPERATOR(learn more)

Generally, it is being considered as short form of if/else statement. This operator takes three oprands which are a condition that followed by a question mark(?), then an expression to execute if the condition is truthy followed by a colon(:), and finally the expression to execute if the condition is false. For example,

//Regular IF/ELSE statement
let isNum = false;
if(typeof 25 === "number"){
  isNum = true;
}
console.log(isNum);//true

//TENARY OPERATOR
let checkNumber = (typeof 25 === "number") ? true : false;
console.log(checkNumber);//true
 
SWITCH STATEMENT(learn more)
It is an alternative way of writing the if/else statement, all we want to do compare one value to multiple different options. For example,
const day = 'monday';
    switch(day){
      case "monday":
        console.log('first day of the week');
        break;
     case "tuesday":
  console.log('second day of the week');
        break;
     case "wednesday":
        console.log('second day of the week');
        break;
      default:
        console.log('weekend');
        break;
    }
    //OUTPUT - first day of the week

From the above example, we pass the expression into switch, here we are passing day. A case cause used to match against expression we passed, basically switch match the expression with each case from the top to bottom until it finds the match. if the first match found then it uses break clause to stop execution and leave the switch statement. if the expression does not match with any of the case clauses then the default clause will be executed. A switch statement can have one default clause.  

122 views

Please Login to create a Question