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

Javascript

This document provides a comprehensive introduction to JavaScript, covering topics such as creating HTML files, writing JavaScript code, variable declaration, data types, type conversion, string methods, template literals, object literals, arrays, loops, functions, and control structures. It includes code examples and explanations for each concept, demonstrating how to use JavaScript effectively. The document serves as a beginner's guide to understanding and writing JavaScript code for web development.

Uploaded by

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

Javascript

This document provides a comprehensive introduction to JavaScript, covering topics such as creating HTML files, writing JavaScript code, variable declaration, data types, type conversion, string methods, template literals, object literals, arrays, loops, functions, and control structures. It includes code examples and explanations for each concept, demonstrating how to use JavaScript effectively. The document serves as a beginner's guide to understanding and writing JavaScript code for web development.

Uploaded by

rajeshmystuff3
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

JAVASCRIPT

Writing first java script code

Create a folder naming javascript and create a file index.html ,and hold shift!tab key to get html
code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Welcome to Javascript</title>
</head>
<body>
<h1>welcome to the world of javascript and have fun</h1>
<script>
alert("hello");
</script>
</body>
</html>

Save and launch server we get alert hello world.

It is good practice to write js code in separate so create app.js file and write alert here and link the
code file in html file as shown below.
Output-

Right click on browser inspect and click on console we can do below operations as well.
Commenting

For single line ---- //


For multiple line ----- select comments and hold control / key

Now write the code in app.js file to get output in console as shown below
VARIABLES

We can declare variable using var ,let and const. var is not used in modern javascript

o/p

Here the output will be Gaurav since name is reassigned to Gaurav from mani.
>For below the output will be undefined since var greeting is not assigned any value but this can be
used when conditions are applied.

If we uncomment 2nd line we get hello in output.

Rules and regulations for variables


We can write variable name by using letter , _ , number , $ ,camelCase,pascalcase
>We cant reassign value to constant we get error

But we can change object value inside the const var as shown below.

We can push or add new numbers inside array as shown below.


We cant change array numbers in const as shown below.

DATA TYPES
Primitive data types – Stored directly in the location of the variable access .Stored in the
stack. Example – String, number, boolean ,null , undefined ,symbol.
//String
const name = "Gowthammi"
console.log(typeof name);

//number
const age= 10;
console.log(typeof age);

//string
const height= "10"
console.log(typeof height);

//boolean
const hassweets= true;
console.log(typeof hassweets);

//number

const weight = 50.567;


console.log(typeof weight);

output
//null

const abc = null;//we are storing a value of nothing


console.log(typeof abc);
output

Undefined
//undefined
let a;//if we dont initialize it witha value ,than it is undefined ,by
default variables are undefined
console.log(typeof a);

Symbol
//symbol

const sym =Symbol();


console.log(typeof sym);
Reference data types – Stored by reference ,stored in heap and points to location in
memory. Eg- Arrays , object literals, functions .
//arrays
const hobbies= ['singing','dancing','movies'];
console.log(typeof hobbies);

//object literals

const person= {
name:" gowthami",
age:25,
};
console.log(typeof person);

output- object

//DATES

const today = new Date();


console.log(typeof today);

output – Object
>
const today = new Date();

console.log(today);
Type conversion and cohesion
//number to a string

let val;

val= String(5+5);

console.log(val);

console.log(typeof val);

console.log(val.length);

output>>

10

String

//boolean to string

let val;
val= String(true);
console.log(val);
console.log(typeof val);
console.log(val.length);

output
true
string
4
//Date to string

val= String(new Date());


console.log(val);
console.log(typeof val);
console.log(val.length);
o/p

//Array to string

let val;
val= String([1,2,3,4]);
console.log(val);
console.log(typeof val);
console.log(val.length);

//conversion using toString()

val=(5).toString();
console.log(val);
console.log(typeof val);
console.log(val.length);
Note – Length is applied only for string
//String to number

let val;
val = Number("5");
console.log(val);
console.log(typeof val);
console.log(val.toFixed(2));

o/p

//Boolean value

let val;
val =Number(true);
console.log(val);
console.log(typeof val);
console.log(val.toFixed(2));

>

let val;
val =Number(false);
console.log(val);
console.log(typeof val);
console.log(val.toFixed(2));
let val;
val =Number(null);
console.log(val);
console.log(typeof val);
console.log(val.toFixed(2));

o/p

//Using parseint()

let val;
val= parseInt("5");
console.log(val);
console.log(typeof val);
console.log(val.toFixed(3));
o/p

//Type cohesion

Here javascript will itself convert and performs action. In the below
val1 which is string added to val2 which will also be converted as
string and gives o/p

const val1= "5";


const val2=6;
const sum= val1+val2;
console.log(sum);
console.log(typeof sum);

STRING AND STRING METHODS

const firstName = "Manikanta";

const lastName = "Nayar";


const age= 25;
const str = "Hello there my name is Mani";
const tags ="Web design , web development,programming";

let val;

// val = firstName + lastName;


//Concatenation
// val= firstName + " " + lastName;

// Append which is same as concatenation

// val= "Gaurav ";


// val +="kamat";

// val = "Hello my name is " + firstName + "and iam " +age;

//Escaping
// val = "That's awesome and i cant wait";

//Length
// val= firstName.length;

//concat()
// val= firstName.concat("",lastName);

//Change case
// val = firstName.toUpperCase();
// val= firstName.toLowerCase();

// val= firstName[2];

//Indexof()

// val= firstName.indexOf("a");
// val = firstName.lastIndexOf("a");

//charAt()

// val= firstName.charAt("2");

//Substring

// val=firstName.substring(0,4);

// slice()
// val= firstName.slice(0,4);

//split
// val= str.split(" ");
// val=tags.split(",");

//replace
// val= str.replace("Mani","Gaurav");
//Includes

// val= str.includes("Mani");
console.log(val);

TEMPLATE LITERALS

const name ="Mani";


const age=25;
const job="Web developer";
const city= "Mangalore";

let html;

//Without using template literals, ES5 , we are going to render HTML to


browser with js ,but this is difficult

// html="<ul><li>Name:" +
// name +
// "</li><li>Age:" +
// age+
// "</li><li>job:" +
// job +
// "</li><li>" +
// city +
// "</li></ul>";
// document.body.innerHTML = html;

//With using template literals(es6)


html=`
<ul>
<li>Name:${name}</li>
<li>Age:${age}</li>
<li>job:${job}</li>
<li>city:${city}</li>
</ul>
`;
document.body.innerHTML=html;
o/p

OBJECT LITERALS

const person ={
firstName: "Mani",
age: 25,
email: "[email protected]",
hobbies: ["eat","sleep","code"],
address :{
city:"Mangalore",
state:"karnataka"
},
//below is method because function inside object
getBirthYear:function(){
return 2020 - this.age;
//this is used to access property of other object
}
};
let val;
val = person;
console.log(val.hobbies[2]);
console.log(val.firstName);
console.log(val.age);

console.log(val.address.city); //accessing child object

console.log(val.getBirthYear());

O/P
//ARRAY OF OBJECTS

const people = [
{
firstName:"Mani",
age:25,
},
{
firstName:"Gaurav",
age:27,
},
];
console.log(people);
console.log(people[0]);
console.log(people[0].firstName);
console.log(people[1].firstName);
//now using loops to print all the first name of array of objects

const people = [
{
firstName:"Mani",
age:25,
},
{
firstName:"Gaurav",
age:27,
},
{
firstName:"Kamat",
age:27,
},
];

for(let i=0; i<people.length; i++) {


console.log(people[i].firstName);
}
o/p

ARRAYS AND METHODS

//Create some arrays


const numbers= [43,56,33,55,88,99,12];
const number2= new Array(222,33,44,555,666);
const fruits =["Apple","orange","banana"];
const mixed =[22,"hello",null,true,undefined];

console.log(numbers);
console.log(number2);
console.log(fruits);
console.log(mixed);
o/p

//get the array length

const numbers= [43,56,33,55,88,99,12];


const number2= new Array(222,33,44,555,666);
const fruits =["Apple","orange","banana"];
const mixed =[22,"hello",null,true,undefined];

let val;
val=numbers.length;
console.log(numbers);
console.log(val);

//check if its an array

const numbers= [43,56,33,55,88,99,12];


const number2= new Array(222,33,44,555,666);
const fruits =["Apple","orange","banana"];
const mixed =[22,"hello",null,true,undefined];

val= Array.isArray(numbers);
console.log(numbers);
console.log(val);
//get a single value

const numbers= [43,56,33,55,88,99,12];


const number2= new Array(222,33,44,555,666);
const fruits =["Apple","orange","banana"];
const mixed =[22,"hello",null,true,undefined];

val= numbers[0];
console.log(numbers);
console.log(val);

o/p

//Insert or replace

val= numbers[0];
numbers[2]=100;
console.log(numbers);
console.log(val);
//find the index value

let val;
val= numbers.indexOf(33);
console.log(numbers);
console.log(val);
o/p

////mutatting the arrayss

//Add a number to the end of an array

// numbers.push(250);
// console.log(numbers);

//add to the front of thr array

// numbers.unshift(120);
// console.log(numbers);
// console.log(val);

//remove the last number from the array

// numbers.pop();
// console.log(numbers);

//remove the first number from the array

// numbers.shift();
// console.log(numbers);

//splicing

// numbers.splice(1,2);
// console.log(numbers);

//reverse the array

// numbers.reverse();
// console.log(numbers);
//concat the array

// val=numbers.concat(number2);
// console.log(numbers);
// console.log(val);

//sort

// val=fruits.sort();//sorting the alphabets


// console.log(val);

// val= numbers.sort();
// console.log(numbers);
// console.log(val);

//to sort in ascending order

// val= numbers.sort(function(x,y) {
// return x-y;
// });
// console.log(numbers);
// console.log(val);

//to sort in descinding order


// val = numbers.sort(function(x,y)
// {
// return y-x ;
// });

//Conditions and comparison

// if(something){
// do something;
// }else{
// do something else
// }

const id= 100;// assignment operator

//equal to
// if (id==100) {
// console.log("yes number is 100");
// }else {
// console.log("sorry not 100");
// }
//not equalto

// if(id !=100){
// console.log("true not 100");
// }else {
// console.log("yes its 100");
// }

//Equal to value and type we use trible equal to (===) to check value
and type of the value

const id= "100";// assignment operator


if(id===100){
console.log("yes the number is 100");
}else {
console.log("its not number but string");
}

//If not given id value it will dispaly no id instead of displaying id


is undefined by using typeof id!== “undefined

//const id= 100;

if (typeof id!== "undefined") {


console.log(id);
}else{
console.log("No id");
}

const id= 100;


if (id>=100) {
console.log("high");
}else {
console.log("low")
}
//if else

const color = 'blue';


if (color === "red") {
console.log("color is red");
}else if (color === "blue") {
console.log("color is blue");
}else {
console.log("some other color");
}

//Logical operator

const age = 25;


if (age>0 && age<12){
console.log('he is an child');
}else if(age>13 && age <20){
console.log('he is an infant');
}else {
console.log('he is an adult');
}

const age = 14;


if(age>16 || age<65 ){
console.log ('he can participate');
}else {
console.log('he cant participate');
}

TERNARY OPERATOR

const id= 100;


console.log(id === 100 ?"yes,correct" : "no its not 100");

o/p

yes,correct

//Loops in java

for (let i=0 ;i<10 ; i++) {


console.log("hie");
}
o/p

prints hie 10 times

const names= ["mani","gaurav","rakesh","microdegree"];


for(let i=0 ;i <names.length ;i++){
console.log(names[i]);
}

o/p

mani

Gaurav

Rakesh

Microdegree

>Here below v is replaced with let coditions

const names= ["mani","gaurav","rakesh","microdegree"];

for ( var v of names){


console.log(v);
}

o/p

mani

Gaurav

Rakesh

Microdegree

While Loop

let i =0 ;
while(i < 10) {
console.log(i);
i++;
}
o/p
// Do while

let i = 10;
do {
i++;
console.log(i);
}while(i<10);

o/p

11

//For in loop

Here x holds the key name that is firstname ,age so in order to get
value we have to put person[x]

const person = {firstName:"Mani", age:25};


for(x in person){
console.log(person[x]);
}

o/p

Mani

25

const person = {firstName:"Mani", age:25};


for(x in person){
console.log(x);
}

o/p

firstName

age

//Function declaration and expression

function greet() {
console.log("hie") ;
}
greet();
greet();

o/p

hie

hie

so here we call the function by name and get o/p as many times we need

function greet() {
return 1995
}
console.log(greet());

o/p

1995

>>

function greet (firstname){


return `Hello ${firstname}`
}
console.log(greet('mani'));

o/p

Hello mani

>>

function greet (firstname = "Gaurav"){


return `Hello ${firstname}`
}
console.log(greet());
o/p

Hello Gaurav
>>

function greet (firstname = "Guarav"){


return `Hello ${firstname}`
}
console.log(greet("Mani"));

o/p

Hello Mani

Here mani will be preceeding and given priority than Gaurav assigned

Function expression

const mul =function (){


return "hello";
};
console.log(mul());

o/p

hello

>>

const mul = function(a){


return a*a;
};
console.log(mul(2));

o/p

>>

const mul = function(a,b){


return a*b;
};
console.log(mul(2,3));

o/p

//IIFE Immediately invokable function expression


(
function(name){
console.log(`${name} ran...`);
}
)("Gow");
o/p

Gow ran…

//declaring variable inside function ,declaring function inside object

const person ={
getBirthday : function (day) {
return `june ${day}`;
},
};
console.log(person.getBirthday(2));

o/p

June 2

//Switch

const color ="yellow";


switch (color) {
case "red":
console.log("color is red");
break;
case "blue":
console.log("color is blue");
break;
default:
console.log("neither red nor blue");

o/p

neither red nor blue

>>

const dayofweek = new Date().getDay();


let day;

switch(dayofweek){
case 0 :
console.log('sunday')
break;
case 1:
console.log('monday')
break;
case 2:
console.log('Tuesday')
break;
case 3:
console.log('wed')
break;
case 4:
console.log('Thu')
break;
case 5:
console.log('Fri')
break;
case 6:
console.log('sat')
break;
}
o/p

wed

Local scope and global scope

Local variable can be accessed only inside the block declared where
global variable can be accessed from anywhere .Local variable is local
to the current block and cant be accessed outside the block. Local
variable has has high precedence than global variable.

//Accessing locally
{
const message ="Hi..;"
console.log(message);
}

o/p

Hi..

//Accessing Globally
{
const message ="Hi..;"
}
console.log(message);

//function

function abc(){
const message = "hi";
console.log(message);
}
abc();

o/p

hi

function abc(){
const message = "hi";
}
console.log(message);
abc();
o/p

uncaught reference error

//Using if

function abc(){
const message = "hi";
if (true) {
const another ="bye";
console.log(another);
}
}
abc();

o/p

bye
function abc(){
const message = "hi";
if (true) {
const another ="bye";
}
console.log(another);
}
abc();

o/p

uncaught reference error

function abc(){
const message = "hi";
if (true) {
const another ="bye";
}
for (let i=0 ;i<5; i++){
console.log(i);
}
}
abc();

o/p

function abc(){
const message = "hi";
if (true) {
const another ="bye";
}
for (let i=0 ;i<5; i++){

}
console.log(i);
}
abc();
o/p

uncaught reference error

//Multiple functions

Here same variable message can be used in different functions

function abc(){
const message = "hi";
console.log(message);
}

abc();

function pqr(){
const message = "bie";
console.log(message);
}

pqr();

o/p

hi

bie

//Global scope

const color="blue";
function abc(){
const message = "hi";
console.log(message);
console.log(color);
}

abc();

o/p

hi

blue
Precedence of local and global variable

const color="blue";
function abc(){
const message = "hi";
const color="red";
console.log(color);
}

abc();

o/p

red

it displays red not blue because local variable takes highest


precedence than global variable

//Let verses variable

>Using let

function start() {
for (let i=0; i<5;i++){
console.log(i);
}
}
start();
o/p

0 1 2 3 4

function start() {
for (let i=0; i<5;i++){

}
console.log(i);
}
start();
o/p

unreference error

>using var

function start() {
for ( var i=0; i<5;i++){
console.log(i);
}

}
start();
o/p

0 1 2 3 4

function start() {
for ( var i=0; i<5;i++){

}
console.log(i);
}
start();
o/p

Note :

//var is functional scope it can be accessed inside the function

//let, const is block scope it can accessed only if it is inside the


block

function start() {
for ( var i=0; i<5;i++){
if(true) {
let color = "blue"; //if we use var,const in let space also
same ouput
console.log(color);
}
}
}
start();
o/p

5 blue

function start() {
for ( var i=0; i<5;i++){
if(true) {
let color = "blue";/if we const also same o/p
}
console.log(color);
}
}
start();
o/p
uncaught reference error
function start() {
for ( var i=0; i<5;i++){
if(true) {
var color = "blue";
}
console.log(color);
}
}
start();

o/p
5 blue

So here var is accessable outside aswell

>>in terms window operspective

var age = 25; // it appends to window object that is it changes the


window property
let age1= 27;//it will not append window object

type window in console log where we get properties


age1 which is described as let cant be seen in window property .it will
not change window property.

Another ex:

Here Window property Attr is changed to var value declared that is


25 .so it overrides window property.

var Attr=25;

o/p

Hence we are not using the var much as it affects the application.

DOM

Once we write Html it will create the Dom object that Document object
module as shown below which can be seen in window property.

You might also like