
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,
- Name must start with a letter, and underscore(_) and or a dollar sign($)
- Name cannot contain spaces
- Name cannot be the same as reserved keywords like if, const, let..
- Name can only contain numbers, letters, underscores and the dollar sign
- By convention, name should not start with an uppercase
- By convention, constant variable can be written in all uppercases
- 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 year = 2023
console.log(year); // 2023
year = true
console.log(year); // true
year = "current"
console.log(year); // current
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 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,
- Number: Integers, decimals
- String: Sequence of characters and put them in quotes
- Boolean: Either true or false
- Undefined: variable is defined but value is not assigned yet
- Null: empty value
- Symbol: value that is unique and can not be changed
- 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
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
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"
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
- 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
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
'use strict';
/*
write your javascript code bellow strict mode
*/
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');
Function Declarations
function test(){
console.log("we are inside a function");
}
//to calling/running/invoking the function
test(); // it will print "we are inside a 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
const addNumbers2 = function (num1, num2){
return num1+num2
}
let sum3 = addNumbers2(10,25)
console.log(sum3);
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 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
function numberTwo(num){
return num/2
}
function addNumbers(num1, num2){
return num1+numberTwo(num2)
}
const sum = addNumbers(5,10);
console.log(sum);
const num1 = 10
const num2 = 12
const num3 = 14
//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]
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]
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)
const person = ['person name',30,'web developer']
Defining object
const person = {
name:"john",
age:41,
job:'retailer',
hobbies:['music','movies','golf']
}
//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"
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
//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
const numbers = [10,11,12,14,15];
for(let i = 0; i < numbers.length;i++){
console.log(numbers[i]);
}
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']
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
let rep = 1;
while(rep <= 10){
console.log(`rep ${rep}`);
rep++
}
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
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
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