In this post 10 days of javascript series youโll learn javascript from beginning this series will be helpful for those who are confuse how to learn javascript and where to start
After completing this 10 days of javascript series you will be going to become a noob to intermediate in javascript after that you can also explore more in javascript by your own
Basics of html & css
Tools you need for this series
Javascript is the language of the web
Write once , run everywhere
Alert using alert()
method
js<script>alert("this is alert");</script>
Alert date using date()
method on onClick()
event
html<button onclick="alert(Date())">The time is?</button>
Right click โค Inspect โค Console / Press F12 key
Similarly CSS, we have to create a new file with the .js extension called index.js or script.js for writing JavaScript in the directory. Now open the index.html file, and just before the closing body tag </body>
, insert this line.
html/* index.html */<script src="script.js"></script>
js// script.js alert("Hello world");
JavaScript is case sensitive therefore a variable name userid
is not the same as Userid
or a function name Myfun()
is not the same as myfun()
jsvar userid = "E1001";console.log(Userid);
In general JavaScript does not require a semi-colon at the end of a statement. If you write two statements in a single line then a semi-colon is required at the end of the first statement.
js// ๐var userid = "E1001";console.log(Userid);// ๐var userid = "E1001";console.log(Userid);
Code written within comments are not processed by the interpreter. Comments are good way to write notations to explain what a script does.
two slashes "/ /"
for single line comment
js// single line comment// alert("Hello world")
/* code here */
for Multi line comment
js/* Multi linecomment *//* var userid = "E1001";console.log(Userid); */
To open the developer console in Google Chrome, open the Chrome Menu in the upper-right-hand corner of the browser window and select More Tools > Developer Tools.
In console you can find all errors, warnings, and messages explicitly logged by JavaScript
Such as an integer, floating point unit,
but is used to represent text
rather than numbers. For example, the word "sumit" and the phrase "I am 20 year old" are both strings. Even "20" could be considered a string,
jsvar Fname = "sumit";console.log(Fname);
The number data type is used to represent integer number , floating point , positive or negative numbers with or without decimal place, or numbers written using exponential notation
jsvar age = 20; // integer numbervar total = 2021.01; // floating numbervar sumtotal = 4.25e6; // exponential notation
It is typically used to store values like yes (true) and (false), on (true) or off (false), etc
jsvar Fname = "sumit";console.log(Fname);console.log(Fname == "sumit"); // trueconsole.log(Fname == "coding"); // false
The undefined data type can only have one value-the special value undefined. If a variable has been declared, but has not been assigned a value, has the value undefined.
jsvar a;var b = "Hello World!";console.log(a); // Output: undefinedconsole.log(b); // Output: Hello World!
A null value means that there is no value. It is not equivalent to an empty string ("") or 0, it is simply nothing.
jsvar c = "";var d = null;console.log(c); //console.log(d); // null
typeof()
operatorVariable means anything that can vary JavaScript includes variables which hold the data value and it can be changed anytime. JavaScript uses reserved keyword var to declare a variable. A variable must have a unique name.
A JavaScript variable must start with a letter (A-Z, a-z)
, underscore (_),
or dollar sign ($),
subsequent characters can also be digits (0-9)
Using the keyword var. For example, var x = 100
. Can be used to declare both local and global variables.
Assigning it a value. For example, x = 100
. It declares a global variable and cannot be changed at the local level.
Variables declared within a JavaScript function, become LOCAL to the function. Local variables have Function scope: They can only be accessed from within the function.
jsfunction Multiply(x, y) {var result = x * y;console.log("Total is: " + result); // output 20}Multiply(4, 5); // call functionconsole.log(result); // error โ ๏ธ
A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it.
jsvar total = 15;function sumof() {console.log("Total is: " + total); // output 15}sumof(); // call functionconsole.log(total); // output 15
In Javascript an array literal is a list of expressions, each of which represents an array element, enclosed in a pair of square brackets '[ ]'
js//Creating an empty arrayvar frontend = [];//Creating an array with four elements.var frontend = ["HTML", "CSS", "JAVASCRIPT", "REACT"];//Display an array elementconsole.log(frontend[1]); // CSS//No need to specify all elements in an array literalvar frontend = ["HTML", , "CSS", "JAVASCRIPT"];console.log(frontend[1]); // undefined
A string literal is zero or more characters, either enclosed in single quotation (')
marks or double quotation (")
marks. You can also use +
operator to join strings.
jsstring1 = "coding";string2 = "sumit";string3 = "First line \n Second line";string4 = "instagram" + ".com";console.log(string1);console.log(string2);console.log(string3);console.log(string4);
An object literal is zero
or more pairs of comma
separated list of property names and associated values, enclosed by a pair of curly braces.
jsvar pages = {username: "codingsumit",name: "Sumit Harijan",Followers: 500,codingbatch: { followers: 55000, post: 230 },};console.log(pages.name); // Sumit Harijanconsole.log("Username: " + pages.username + " Followers : " + pages.Followers);// Username: codingsumit Followers : 500console.log("Followers of codingbatch :" + pages.codingbatch.followers);// Followers of codingbatch :55000
Boolean literals represent only two values true
or false
. And in Javascrip the value of 1 is assumed as true and the value of 0 is assumed as false
js/*If comparison or logical operator is not used JStries to figure out if the value is "truth".*/var isArray = true;if (isArray) {console.log("Yes it is an array!");}//Empty string (""), number(0), undefined, null are false value.var username = "";if (username) console.log("My name is : " + username);var followers = 0;if (followers) console.log("Your roll no. is " + followers);var address;if (address) console.log("Your name is " + username);
jsconsole.log(18 % 5); // output 3var num = 6;console.log(--num); // output 5console.log(++num); // output 7console.log(-num); // output -6
jsvar a = 3;var b = 4;console.log((a += b)); // output 7console.log((a *= b)); // output 12console.log((a /= b)); // output 3console.log((a -= b)); // output 3console.log((a %= b)); // output 3
jsconsole.log(4 == "4");// true :- value equalconsole.log(4 === "4");// false :- value equal but type not sameconsole.log(4 != 3);// true :- 4 is not equal to 3console.log(4 !== "3");// true :- value 4 & type both are not same
jsconsole.log(6 < 10 && 3 > 1); // trueconsole.log(15 == 10 || 3 < 1); // trueconsole.log(!(4 == 5)); // true
The conditional operator is used as a shortcut for standard if statement. It takes three operands. Syntax : Condition ? expr1 : expr2
jsscore = 75;var result = score >= 40 ? "Win" : "Lose";console.log(result); // output :- Winscore = 39;var result = score >= 40 ? "Win" : "Lose";console.log(result); // output :- Lose
The comma operator is used to evaluate multiple expressions in one line.
jsfor (var i = 0, j = 10; i <= 3; i++, j++) {console.log("Floor no : " + i + " Flat No : " + j);}
Lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
jsfunction User(name, age, nationality) {this.name = name;this.age = age;this.nationality = nationality;}var admin = new User("sumit", 20, "Indian");console.log(admin.nationality); // output : Indianconsole.log(admin.name); // output : sumitconsole.log(admin.age); // output : 20
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
jsvar admin = {codingbatch: "sumit",codingsumit: "smthari",};console.log(admin.codingbatch); // output:- sumitdelete admin.codingbatch;console.log(admin.codingbatch); // output:- undefined
The in operator returns true if the specified property is in the specified object or its prototype chain.
jsconst user = {name: "sumit",profession: "web developer",age: "20",nationality: "indian",};console.log("name" in user); // truedelete user.name;console.log("name" in user); // false
The instanceof operator is used to check the type of an object at run time. The instanceof operator returns a boolean value that indicates if an object is an instance of a particular class
jsvar newstring = new String("sumit"); // string objectconsole.log(newstring instanceof String); // returns truevar newdate = new Date(); // date objectconsole.log(newdate instanceof Object); // returns trueconsole.log(newdate instanceof Date); // returns trueconsole.log(newdate instanceof String); // returns falsevar newNumber = new Number(); // number objectconsole.log(newNumber instanceof Number); // returns true
The this operator is used to refer the current object. In general, this refers to the calling object in a method.
jsvar person = {firstName: "Sumit",lastName: "Harijan",fullName: function () {return this.firstName + " " + this.lastName;},};// Display data from the object:console.log(person.fullName()); // sumit Harijan
The typeof operator is used to get the data type of its operand
jsvar name = "sumit";var age = 20;var user = {firstName: "sumit",lastName: "harijan",};console.log(typeof name); // stringconsole.log(typeof age); // numberconsole.log(typeof user); // object
The instructions written in a program in a programming language are known as statements.
There is a difference types of statements in javascript but for now we gonna learn only basic
A block statement groups zero or more statements. In languages other than JavaScript, it is known as a compound statement.
jsvar a = 40;{var a = 200;}console.log(a); // 200
Executes a group of statements if a logical condition is true. Use the optional else clause to execute another group of statements.
jsfunction grade(marks) {if (marks > 90) console.log("Grade A+");else if (marks > 80) {console.log("Grade A");} else if (marks > 70) {console.log("Grade B");} else {console.log("Grade C");}}grade(85);grade(55);
The switch statement allows to make a decision from the number of choices.
jsfunction marksgrade(marks) {grade = marks;switch (grade) {case "A+":console.log("marks > 90");break;case "A":console.log("marks > 80");break;case "B":console.log("marks > 70");break;case "C":console.log("Marks < 60");break;default:console.log("Wrong grade");}}marksgrade("A+"); //"Marks >= 90"marksgrade("L"); //"Wrong grade"
The break statement is used to terminate a loop, switch or label statement.
jsfor (var i = 1; i < 19; i++) {if (i == 4) {break;}console.log(i);}
The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
jsfor (var i = 1; i < 8; i++) {if (i < 4) {continue;}console.log(i);}
jstry {alertmsg("Wrong call");} catch (e) {console.log("Error Message: " + e.message);console.log("Error Name: " + e.name);}
The return statement returns a value and exits from the current function.
jsfunction mul(a, b) {return a * b;}console.log(mul(4, 5)); // 20
js// Syntaxfunction name(parameter1, parameter2, parameter3) {// code to be executed}
For example, to declare a function that calculate the sum of argument passed to it,
You can do it in one of two ways
js// Example -1function cube(n) {return n * n * n;}// Example - 2var cube = function (n) {return n * n * n;};
Calling the function actually executes the instructions written within the function with the indicated parameters.
jsconsole.log(cube(2)); // output : 8
In JavaScript there are two types of scope:
js//Global scopevar name = "sumit";function namefun() {console.log("I can display name" + " " + name);}namefun();// Function scopefunction userfun() {var user = "smthari";console.log("I can display user" + " " + user);}userfun();console.log(typeof user); // undefined
In JavaScript all values except the primitive types of JavaScript (true, false, numbers, strings, null and undefined)
are objects.
You can create an object in two ways :-
js/* 1) The syntax of creating objectusing object literal */var object = {};/* 2) The syntax of creating object directlyusing instance Object oriented way */var objectname = new Object();
You can specify properties when creating an object or later. Property name can be only a string. Properties are separated by commas.
jsvar user = {fname: "Sumit",lname: "Harijan",age: 20,fullname: function () {return this.fname + " " + this.lname;},};
The following code demonstates how to access a property's value.
jsvar name = user.fullname();console.log(name); // Sumit Harijanvar age = user.age;console.log(user.age); // 20
The following codes show how to add a new property or modify an existing one.
jsvar name = user.fullname();var age = user.age;user.fname = "smthari";console.log(user.fname); // smthariuser.age = 21;console.log(user.age); // 21