0% found this document useful (0 votes)
29 views

JAVASCRIPT

Uploaded by

insha a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

JAVASCRIPT

Uploaded by

insha a
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

JAVASCRIPT

JAVASCRIPT 1
VARIABLES
//1. decleration
let x;
//2. assignment
x=200;
//printing
console.log(x);

//we can do decleration and assignment in one step:

let x=200:
console.log(x);

${} //placeholder

Datatypes

JAVASCRIPT 2
//NUMBERS
let age=25;
let price=10.99;
let gpa=2.3;

console.log(typeof gpa);
console.log(typeof price);
console.log(typeof age);
console.log(`You are ${age} years old.`);
console.log(`The price is $${price}.`);
console.log(`Your gpa is ${gpa}.`);

//OUTPUT
number
number
number
You are 25 years old.
The price is $10.99.
Your gpa is 2.3.

//STRINGS

let name="Bro"; //we can use single quote or double quote


let favouritefood="Pizza";
let email="[email protected]" //strings can include numbers,
but can't use for mathematical operations.

console.log(typeof name);
console.log(typeof favouritefood);
console.log(typeof email);

console.log(`My name is ${name}.`);


console.log(`I love ${favouritefood}.`);
console.log(`My email is ${email}`);

//OUTPUT
string

JAVASCRIPT 3
string
string
My name is Bro.
I love Pizza.
My email is [email protected]

//BOOLEAN

let online=true;
let forSale=false;
let isStudent=true;

console.log(typeof online);
console.log(`is he online?: ${online}`);
console.log(`is this car fo sale? ${forSale}`);
console.log(`Is this student enrolled? ${isStudent}`);

//OUTPUT

boolean
is he online?: true
is this car fo sale? false
Is this student enrolled? true

EXCSERCISE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, init
ial-scale=1.0" />
<title>Document</title>
</head>

<body>
<p id="myName">What is your name?</p>

JAVASCRIPT 4
<p id="myAge">What is you age?</p>
<p id="status">Are you a student?</p>

<script>
let fullName = "Rob";
let age = 23;
let isStudent = true;

document.getElementById("myName").textContent = `My n
ame is ${fullName}`; //getElementById is used to fetch the
element with a particular id.
document.getElementById("myAge").textContent=`I am
${age} years old.`; //textContent is used to change the tex
t
document.getElementById("status").textContent = isStu
dent;
</script>
</body>
</html>

KEYWORDS
Their meaning and purpose is already defined within the Javascript.

Must be written in lowercase letters.

Should not be used as identifiers or user defined names.

1. var, let, const


//These three keywords are used to declare a variab
le.
//var can be redeclared and reassigned.
var x=5;
x=10; //reassignment
var x=15; //redecleration

//let cannot be redeclered but can be reassigned.


let x=5;
x=15; //reassignment

JAVASCRIPT 5
let x=30; //Error shows

//const can neither be redeclered nor be re assigne


d.
const x=15;
x=15; //shows error
const x=15; //error shows

2. if, else, else if


//Used for conditional statement

if execute a code block if the condition inside


if statement is true
if (condition) {
// code to execute if condition is true
}

code block under else statement will execute if


the if condition is false.
if (condition) {
// code to execute if condition is true
}
else {
// code to execute if condition is fals
e

Specifies a new condition to test if the first


condition is false.
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if none of the above conditions are
true
}
3. for, while, do...while

JAVASCRIPT 6
for: A loop with a counter, usually used when the number of
iterations is known.
for (let i = 0; i < 5; i++) {
console.log(i);
}
//OUTPUT
0
1
2
3
4
while: A loop continues to run as long as the condition is
true.
let i=0;
while(i<5){
console.log(i);
i++;
}
//OUTPUT
0
1
2
3
4
do...while: Similar to while loop. But it guarantees at lea
st one iteration, as the condition is checked after the loo
p body.

let i = 0;
do{
console.log(i);
i++;
} while (i<5);
//OUTPUT
0
1
2
3

JAVASCRIPT 7
4
4. function: functions can be called using their naame and
passing any required arguments.

function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("insha"));

//OUTPUT
Hello, insha!

function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet(123));
//OUTPUT
Hello, 123!

5. return:Used to exit a function and return a value.

function add(a, b) {
return a + b;
}
let sum = add(5, 3); // sum is 8

5. switch:

let day = 3;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');

JAVASCRIPT 8
break;
default:
console.log('Other day');
}

//OUTPUT
Wednesday

let day = 2;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
default:
console.log('Other day');
}

//OUTPUT
Tuesday

let day = 5;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
default:

JAVASCRIPT 9
console.log('Other day');
}

//OUTPUT
Other day

7. try, catch, finally

Used for error handling.


try: wraps code that may throw an error.
catch : executes if an error occur in try block.
finally : executes after try and catch block regardless of
whether the error occured.

try {
// code that may throw an error
let result = riskyOperation();
} catch (error) {
console.error(error); // handle the error
} finally {
console.log('This runs no matter what');
}
8. class

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
console.log(`Hello, my name is ${this.name} and I a
m ${this.age} years old.`);
}
}

let person1 = new Person('Alice', 30);


person1.greet();

JAVASCRIPT 10
//Output
Hello, my name is Alice and I am 30 years old.

9.this : analogous to self

class Car {
constructor(brand) {
this.brand = brand;
}

display() {
console.log(`This car is a ${this.brand}`);
}
}

let myCar = new Car('Toyota');


myCar.display(); // This car is a Toyota

10. new

let date = new Date(); // Creates a new Date object

11. null and undefined

null: intentional absence of any object value.


undefined: uninitialised variable or absent value.

let a = null;
let b;
console.log(b); // undefined

12. true and false

let isRaining = false;


if (!isRaining) {
console.log('You don\'t need an umbrella.');
}

JAVASCRIPT 11
//OUTPUT
You don't need an umbrella.

13. import and export

we could import and export code from other modules to the c


urrent file.

To do that in html file, we link our .js file like this.

<script>src="index.js"</script>

add 'type' attribute to this code inorder to make the file


a module.

<script> type ="module" src="index.js"</script>

index.js is the file where we want to import our code.


mathUtil.js is the file from which we export the code.

in mathUtil.js:

export const Pl = 3.14159;


export function getCircumference(radius){
return 2 * PI * radius;
}
export function getArea(radius){
return PI * radius * radius;
}
export function getVolume(radius){
return 4 * PI * radius * radius;
}

in index.js:
import{PI, getCircumference, getArea, getVolume} fr
om './mathUtil.js';

JAVASCRIPT 12
console.log(PI);
const circumference = getCircumference(10);
const area = getArea(10);
const volume = getVolume(10);

console.log(`${circumference.tofixed(2)}cm`);
console.log(`${area.tofixed(2)}cm^2`);
console.log(`${volume.tofixed(2)}cm^3`);

//output
3 .14159
62.83cm
314.16cm^2
1256.64cm^3

OPERATORS
Comparison Operators
== equal to
!= not equal to
=== strict equal to
!== strict not equal to

Equal to

var a=5;
var b= 5;
var c= "Monica"

console.log(a==5); //true
console.log(b=='5'); //true
console.log(c=="monica") //false due to case sensitivity of
string

Not equal to

JAVASCRIPT 13
var a = 4;
var b = "Monika";

console.log(a!=3); //true
console.log(b!="Monika"); //false

Strict equal to

var a=10;

console.log(a===10); //true
console.log(a==='10'); //false .... because strict equal to
check the datatype also

Strict not equal to

a=2;
b="Monica"

console.log(a !== 2); //false


console.log(a !== '2'); //true
console.log(a !== "monica"); //true

Greater than

a=20;
b=10;

console.log(a>b); //true

less than

a=10;
b=20;

JAVASCRIPT 14
console.log(a<b); //true

less than or equal to

a=2;

console.log(a<=3); //true
console.log(a<=2); //true

less than or equal to

a=2;

console.log(a>=3); //false
console.log(a>=2); //true
console.log(a>=1); //true

CONDITIONAL OPERATORS

Ternary operators
Short form of if else condition.

let age =18;


let canVote = (age >= 18) ? "Yes" : "No";
console.log(canVote);

//Output : Yes

Logical Operators
AND : true if both the conditions are true.

OR : true if either of the conditions is true.

NOT : true if the opposite of condition’s truthiness.

JAVASCRIPT 15
= assigning value to an operator

== for the comparison of operators but ignores datatype

=== for the comparison of operators but only true if datatypes


also same.

Undefined vs Null
undefined : A variable has been declared but not yet been assigned.

let x;
console.log(x); //logs undefined

null : it is an assignment value. A variable has been declared and given a


value null.

let y = null;
cinsole.log(y); //logs 'null'

Block scope and function scope


In JavaScript, the whole document is global scope and all other functions
and variables contained in global scope.

Function Scope: When a variable is declared inside the function, it is only


accessible within that function and cannot be used outside.

variables declared inside the curly braces are called block scope.

let and const are also block scope. since the variables are used within a
particular block. let used to declare a variable which can be changed as
program progress, while const is a variable that can be declared inside the
program which cannot be changed throughout the program.

var : functions scoped

let : block scoped

const: block scoped

JAVASCRIPT 16
function hello() // calls a function
{
if (true)
{
var a = 'Javascript'; //function scoped
let b = 'c++'; //block scoped
const c = 'Python'; //block scoped
console. log(a) ; //logs Javascript
console. log(b) ; //logs c++
console. log(c) ; //logs Python
}
console. log("outside If statement") //logs outside If
statement
console. log(a) ; //logs Javascript since var is a func
tion blocked element.
console. log(b) ; //logs reference error since if block
has ended
console. log(c); //logs reference error since if block
has ended.
}
hello() ;

A variable that declares outside the function : Global function

Shadowing and Illegal Shadowing


when a variable is declared and assigned a value inside a certain scope,
then it is reassigned in another block, reassigned value will be the new
assigned value. and after that scope. the value will be again the previously
assigned value.

function func() {
let a = 'Geeks';

if (true) {
let a = 'GeeksforGeeks'; // New value assigned
console.log(a);

JAVASCRIPT 17
}

console.log(a);
}
func();

//outpt

//GeeksforGeeks
//Geeks

illegal shadowing: declaring var in the outside block and then declaring new
variable in the inside block using let is legal

but reverse is illegal

function func() {
var a = 'Geeks';
let b = 'Geeks';

if (true) {
let a = 'GeeksforGeeks'; // Legal Shadowing
var b = 'Geeks'; // Illegal Shadowing
console.log(a); // It will print 'GeeksforGeeks'
console.log(b); // It will print error
}
}
func();

Pass by value and Pass by reference


Pass By Value

let a = 10;
let b = a;

a = 20;

JAVASCRIPT 18
console.log(a); //logs 20
console.log(b); //logs 10

Here variable a declared and assigned a value of 10.

then var b declared and assigned variable a; which means the memory
space labelled by variable b stores the value of memory space labelled by
variable a, i.e. 10.

Then reassign the variable a to 20

But since we passed only the value to a, the change in variable a doesn’t
affect the variable b.

Pass by reference

let obj1 = {value : 10};


let obj2 = obj1;

obj1=20;

console.log(obj1.value); //logs 20
console.log(obj2.value); //logs 20

Here obj1 assigned a value 10

obj2 pointed to the value of obj1

therefore now the value in obj2 is 10

then obj1 is reassigned to 20

Since obj2 is pointed towards the value of obj1, the value in obj2 also
changes corresponding to obj1. i.e. 20

Type coercion
This is basically the technique of converting a value from one datatype to
another datatype

code conversion and code coercion is doing the same thing but with one
key difference.

JAVASCRIPT 19
type coercion is implicit ; can be automatically changed to another
datatype.

type conversion is either explicit or implicit

let a = 10;
let b = '20';

let sum = a + b;

console.log(sum); //logs 1020

JAVASCRIPT 20

You might also like