top of page

JavaScript Basics

  • Writer: sondip poul singh
    sondip poul singh
  • May 15, 2019
  • 9 min read

"JAVASCRIPT-----i make the webpages alive"

JavaScript can execute not only in the browser, but also on the server, or actually on any device that has a special program called the JavaScript engine.

The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

Different engines have different “codenames”. For example: V8 – in Chrome and Opera. SpiderMonkey – in Firefox. ******************************************************************************************** 1.write <script> //to write javascript code alert("my name is sondip"); </script>

2. external javascript <script src="path to source"></script>

3. <script src="some path"> //not right creates error //some code </script>

4. <script> [1, 2].forEach(alert);//returns 1 then 2 in alert </script>

5. "use strict" directive switches the engine to the “modern” mode, changing the behavior of some built-in features. ********************************************************************************************

<!-- "Variables"--> ->use let to declare a variable(modern style let name="sondip") ->var was a old school method to declare variable ->const is used to declare constant values which cannot be changed later (const budget=1000,we conventionally write BUDGET in case of const) ->variables can be declare without let or var when "use strict" is not used but its a bad practice ->let name="sondip",age=23,salary=15000; is all right ->variables names can be start with _ or $,not with numbers or reserved keys

<!--**************************************************************************************->

<!--data types--> https://javascript.info/types There are mainly seven types(check out the link for details) 1.numbers 2.strings 3.null -> “reference to a non-existing object” or a “null pointer” 4.undefined -> value is not assigned 5.object 6.symbol ->used to identify each object uniquely 7.typeof

some quicky: ->use ``(backtics) to add in string exm: let name="susmoy"; alert(`his name is ${name}`)

->object is a complex data type ->typeof something or typeof(something) returns the type

******************************************************************************************** #TYPE CONVERTION# ***************** ->String(something)//to change in string ->Number(something)//to change in number ->Boolean(something)//to change in true/false

******************************************************************************************** operators ->putting a + sign in front of a string make it int ->2+1+'5' returns 35 which is string ->unary operator are same as other prog. languages ******************************************************************************************** string comparison strict comparison ******************************************************************************************** ->alert(); ->prompt('string',default value); ->confirm('string'); ******************************************************************************************* if else loop same ->ternary operator if else shortcut (let accessAllowed = (age > 18) ? true : false;) ->multiple ? is possible

<script> let age = prompt('age?', 18); let message = (age < 3) ? 'Hi, baby!' : (age < 18) ? 'Hello!' : (age < 100) ? 'Greetings!' : 'What an unusual age!'; alert( message ); </script>

******************************************************************************************* logical operators -> && returns the first falsy value -> || returns the first truthy value ->The precedence of AND && operator is higher than OR || ***************************************************************************************** loops are same as c++ ,break ,continue but what if we want to break the outer loop in some certain condition. <script> outer: for (let i = 0; i < 3; i++) {

for (let j = 0; j < 3; j++) {

let input = prompt(`Value at coords (${i},${j})`, '');

// if an empty string or canceled, then break out of both loops if (!input) break outer; // (*)

// do something with the value... } } alert('Done!'); </script>

->switch cases switch (a) { case 3: alert( 'Too small' ); break; case 4: alert( 'Exactly!' ); break; case 5: case 6: alert( 'Too big' ); //case 5 and 6 have the same code to share break; default: alert( "I don't know such values" ); } ******************************************************************************************* #Functions:

function name(parameters) { //codes here }

->functions can be asssiged as varibales let name=function take_name{ prompt('enter your name','default name'); } ->functions can also be passed as parameter of a function.we call this type of functions as callback funtion. function ask(question, yes, no) { if (confirm(question)) yes() else no(); }

ask( "Do you agree?", function() { alert("You agreed."); }, function() { alert("You canceled the execution."); } );

here yes no function in ask is called as callback funtion.The idea is that we pass a function and expect it to be “called back” later if necessary.

************************************************************************** https://javascript.info/debugging-chrome(*** interesting)

|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

OBJECTS In javascript object is a data type that can hold collection of various data.Its almost like a dictionary in python.An object has properties.A property is a “key: value” pair, where key is a string (also called a “property name”), and value can be anything.

an into example:

let user={ name:"sondip", age:24 }

1.creating a object: to create object we write let user={} //https://javascript.info/object for image and explanation

2.adding properties:

let user={ name:"sondip", age:24 "priyo khabar":"meat" //when more then one word use " " };

user.occupation="student" //adding a new user["main height"]=5 //adding a new also

let fruit = prompt("Which fruit to buy?", "apple"); //taking value from prompt let bag = {}; bag[fruit] = 5; //now its become let bag={apple:5} //it can be accessed by bag.apple which will return 5

3.Accessing alert(user.name); alert(user.["priyo khabar"]) //for more then one words

4.deleting a property: delete user.name; delete user["priyo khabar"]

5.keywords can be used as property key name,its valid.

6.functions can return objects and those objects can be assigned to a variable which will work as a object then.

<script> function makeUser(name, age) { return { name: name, age: age // ...other properties }; }

let user = makeUser("John", 30); alert(user.name); // John </script> if the key and keyvalue have the same name we can write return {name,age}

7.to check the object keys we use "in" i.e ("key" in object) "key must be string" in case of for loop for(let k in user) { alert(k); alert(user[k]) }

8.finally the key values are automatically sorted if they are in integer format.In case of the strings the keys are unsorted and remains the same as they appeared in the order.To get the exact order put a "+" sign before them.

sorted: let codes = { "49": "Germany", "41": "Switzerland", "44": "Great Britain", "1": "USA" };

for (let code in codes) { alert(code); // 1, 41, 44, 49 }

exact same: let codes = { "+49": "Germany", "+41": "Switzerland", "+44": "Great Britain", "+1": "USA" };

for (let code in codes) { alert( +code ); // 49, 41, 44, 1 }

9.same objects are accessed by reference.(***)

********************************************************************** Garbage collection: when any reference is deleted from the objects then it will be throw in trash automatically.

->Symbol type is a unique identifier.In object keys are by default string,which can be replaced by symbol

->objects can be transformed in primitive types (in string,int) etc. ************************************************************************

->this pointer is used in objects or outside the object to get access to the object, a method can use the this keyword. example: <script> let user = { name: "John", age: 30,

sayHi() { alert(this.name); }

};

user.sayHi(); // John </script>

to get access from outside: <script>

let user={ name:"nabil", age:34, };

function say() { alert(this.name); }

user.kotha=say; //we can write methods like this //A method is similar to a function, but is internal to part of a class. The term method is used almost exclusively in object-oriented programming.

user.kotha();//to access the methods(aka function) use ()

</script>

Other use of this pointer in two different objects is like: <script> let user = { name: "John" }; let admin = { name: "Admin" };

function sayHi() { alert( this.name ); }

// use the same functions in two objects user.f = sayHi; admin.f = sayHi;

// these calls have different this // "this" inside the function is the object "before the dot" user.f(); // John (this == user) admin.f(); // Admin (this == admin)

</script> ************************************************************************************** Constructor and new: we use new to create similar objects when necessary.

function User(name) { this.name = name; this.isAdmin = false; }

let user = new User("Jack");

alert(user.name); // Jack alert(user.isAdmin); // false

aikhane function name ta capital word diye suru. new diye akta notun object create korlam. function ta actually akta object return kore. so we get let user={ name:jack, isAdmin:false, }; *********************************************************************************** Objects Vs primitives:(OBJECT WRAPPER also)

the question is whether the primitives are object or not? ans: no they are not.

now let us see a example: let name="sondip"; alert(name.toUpperCase()); //prints SONDIP

let number=1.237521 alert(number.toFixed(2)) //prints 1.24

so if they are primitives how are they accessing those methods.In this case javascript introduce a special feature called "object wrapper".So how does it work?

->take a primitive and wrap it as object,then access the method ->returns the result and the special object is destroyed ->back in its primitive form

******************************************************************************** Numbers type in details: <script>

alert(1e4)//10000 alert(0xff)//255

//number conversion let num=15; alert(num.toString(2));//1111 alert(num.toString(8));//17 alert(num.toString(16));//f

//some math functions let n=125.6567803 alert(Math.floor(n));//125 alert(Math.ceil(n));//126 alert(Math.round(n));//126 nearrest number alert(Math.trunc(n));//125 point er por sob baad alert(n.toFixed(2)); //125.66 round and return 2 place after point //toFixed returns string (for int alert(+n.toFixed() )) alert(Math.max(12,34,1,45));//45 alert(Math.min(1,2,0,32,-1));//-1 alert(Math.random()); alert(Math.pow(3,2));

//some other useful methods let dam="100$"; alert(+parseInt(dam)); //returns 100 alert(typeof(+parseInt(dam))); alert( parseFloat('12.3.4') ); // 12.3

</script>

****************************************************************************** SOme strings:

<script> /*Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.*/

//https://jrgraphix.net/r/Unicode/0980-09FF bangla unicodes alert(`${"\u0986"}${"\u09AE"}`) //returns bangla amm...lol alert( "\u{1F60D}" ); // 😍, a smiling face symbol (another long unicode)

let name="sondip"; alert(name.length); // 6 not length()

let sen="my name is khan"; alert(sen.length);//15

for(let char of name) { alert(char.toUpperCase()); } //remember Strings can’t be changed in JavaScript. //It is impossible to change a character. //finding substring

let str="something is wrong cause it is wrong"; alert(str.indexOf('is'));//10 alert(str.indexOf('is',15)) //28 is kintu 15 er pore alert(str.indexOf("right"));//-1 khuje na paile alert(str.lastIndexOf('is'));//28 pichon theke search

//to find both of them

let sub="is"; let pos=0; while(true) { let find=str.indexOf(sub,pos); if(find==-1) break; alert(`found at position ${find}`); pos=find+1; } //to get a substring use slice let strr = "stringify"; alert( strr.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5) alert( strr.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0 let str2 = "stringify"; alert( str2.slice(2) ); // ringify, from the 2nd position till the end </script> ***************************************************************************** playing with arrays in javascript: Arrays hold a collection of elements or properties.But hold on!Doesnt object also do the same thing.The ans is yes.But sometimes we need ordered collection.Objects are not meant to create in this purpose.We just cant insert a new property and say we want it between the existing ones.In this case we use Array.

let arr=["apple","orange","pinepple"]; ->starts with avariable ->ends with a semicolon

some basic operations:

<script> let name=["sondip","sujon","pritom"]; alert(`${name}'s length is ${name.length}`); alert(name[0]);//sondip name[0]="susmoy";//changing the values alert(name[0]);//susmoy

for(let n in name) //accessing in for loop { alert(name[n]); } </script> One interesting fact is that we can use mixed values in the array.as example <script> let arr = [ 'Apple', { name: 'John',age:18 }, true, function() { alert('hello'); } ]; alert( arr[1].name ); // John alert(arr[1].age)//18 arr[3](); // hello </script>

So in the above example we can see that we can use object,function ,bool values etc in just an single array.Thats cool!

Arrays can be used as queue or stack in javascripts very easily.They allow you to add/remove elements both to/from the beginning or the end. In computer science the data structure that allows it is called deque.

methods work in the end of the array: let num=[1,2,3,4]; num.push(5) //1,2,3,4,5 num.pop() //1,2,3,4

methods work in the start of the array: num.shift()//2,3,4 num.unshift(5)//5,2,3,4

Methods push and unshift can add multiple elements at once:

let fruits = ["Apple"]; fruits.push("Orange", "Peach"); //adding in end fruits.unshift("Pineapple", "Lemon");//adding in beginning alert( fruits ); // ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]

So in case of queue->FIFO->use pop() and unshift() In case of stack->LIFO->use pop() and push()

*arrays are special type of objects *push+pop is faster(only delete or add in last) *shift+unshift is slower(add/delete in first and indexs are shifted)

for loops in array:

normal use: let arr = ["Apple", "Orange", "Pear"]; for (let i = 0; i < arr.length; i++) { alert( arr[i] ); }

N:B->The length property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one.

use direct: let fruits = ["Apple", "Orange", "Plum"]; for (let fruit of fruits) { alert( fruit ); }

access elements: SHOULD BE AVOIDED let arr = ["Apple", "Orange", "Pear"]; for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear }

#MORE ON ARRAYS:

So now if we want to delete array elements from any position what should we do? check out the followings:

<script> let numbers=[1,2,3,4]; delete(numbers[2]); alert(numbers); //returns 1,2,,4 //so delete method delete the elements but not compress the array //array[2]=3;//returns error //so we use splice method here numbers.splice(2,0,3); alert(numbers);//returns 1,2,3,,4 thats not what we want //so what can we do is delete elements by spice and also add elements when needed

//array_name.splice(kotha theke suru korbo,koita element delete korbo,add element,add element...) let num=[1,2,3,4,5]; num.splice(2,2)//position (2+1)=3 a jaw,3 no soho 2 ta element delete koro //returns 1,4,5...3,4 ai 2 ta deleted alert(num); num.splice(2,0,3,4,6)//pos 3 a jaw kono element delete koro na,3,4,6 add koro alert(num); //so now we can add any numbers of element and delete any numbers at any position //thats a very cool feature i think

another exapmle with strings: let arr = ["I", "study", "JavaScript", "right", "now"]; arr.splice(0, 3, "Let's", "dance"); alert( arr ) // now ["Let's", "dance", "right", "now"] </script>

We can also take the deleted elements as array and work with them. Thats how we work with the sub_array: <script> let num=[1,2,3,4,5]; let sub_array=[num.splice(2,2)]; alert(sub_array);//3,4 sub_array.splice(0,0,1,2); alert(sub_array);//1,2,3,4 </script>

Another Example: <script> let numbers=[1,2,3,4,5]; let sub_array=numbers.splice(2,2);//3,4 let new_array=numbers.concat(sub_array,[1,7],19,0); alert(new_array)//1,2,5,3,4,1,7,19,0 alert(new_array.sort());//sort as string alert(new_array.sort((a,b)=>a-b));//ascending sort alert(new_array.sort((a,b)=>b-a));//descending sort </script>

Foreach Loop in array: <script> let names=["sodnip","susmoy","suppriya"]; names.forEach(alert)//returns names sequentially names.forEach(item=>alert(item))//returns name sequentially also names.forEach((item,index,array)=>{alert(`${item} is in ${index+1} in ${array}`)}) //sondip is in 1 in sondip,susmoy,suppriya ...goes on </script>

Searching in the array:

There are three methods to find array elements. 1.indexOf()->used when we know the position(ex:arr.indexOf("susmoy")) 2.find()->to find a specific element,returns true when the element found(a.find()) 3.filter()->serach whole array even if find the element.It is needed cause sometimes we have multiple conditions or same value more then one time in the array

<script> //first type let loc=["dhaka","nepal","india"]; alert(loc.indexOf("dhaka"));// returns 0

//second type let stu=[ {name:"sondip", id:1},//its an item for the stu array {name:"alo", id:2}, {name:"dipu", id:3}, ]; let student=stu.find(item=>item.id==3);//returns the whole item //and as the item is an object we can write alert(student.name);

//third type let users = [ {id: 1, name: "John"}, {id: 2, name: "Pete"}, {id: 3, name: "John"} ]; let someUsers = users.filter(item => item.name=="John"); alert(someUsers.length); // 2 karon duibar John paise id 1 r 3 a </script>

Comments


bottom of page