Skip to main content

Mastering the Basics of JavaScript: A Quick and Comprehensive Guide

JAVASCRIPT

Javascript is a client-side programming language. It basically uses for changing the behavior of simple HTML at occurring an event by clicking, cursor hovering, and key pressing.

Javascript writes in '.html' file, and '.php' file internally and externally with the extension of '.js'.

In HTML, You can write javascript code anywhere but head tags (<head> javascript code </head>) are recommended.

Note: * JQuery is a Javascript library that has pre-built functions of javascript. AJAX is a Javascript Framework that allowed changes in the data and behavior of a page without reloading.


SYNTAX:


'<script type="text/javascript">' (Open tag)  and   '</script>' (Close tag)


DATATYPE:

number (2, 2.5, 2.56e45)
string ('java', "script", '5')
boolean (true, false)
object (all types of arrays)



OPERATORS:

Arithmetic Operators (+, -, *, /, %, **)
Increment/Decrement Operators (++$i, $i++, --$i, $i--)
Assignment Operators (+=, -=, *=, /=, %=)
Comparison Operators (==, ===, <=, >=, !=, !==)
Logical Operators (and, or, !, &&, ||, &, |, ~, ^, >>>, >>, <<)
String Operators (+(Temperory Append -> Concatenation Operator))
Conditional Operators ((Ternary) $x = expr1 ? expr2 : expr3)
Type Operators (typeof variable (You can check type of any variable), instanceof variable (Returns true if an object is an instance of an object type))




VARIABLE:

Variable creates with 'var' keyword in javascript. A variable created in Javascript with the prefix '$' and '_' or only starts with letters.


var x = 10; (number)
var y = "Javascript"; (string)
var z = 2.56; (number)
var a = 2.56e45; (number)
var b = true; (boolean)
var c = [2, 3, 4, 8]         (Indexed array --> object)
var c = {name:'Atul', email: 'atul@gmail.com'}         (Associative array --> object)



OUTPUT:

1) document.write('text'); //Use for testing purpose
2) console.log('text'); //display in browser's console window (press F12 / Fn + F12)
3) document.getElementByClassName('class_name').innerHTML = 'text'.
4) window.alert('text'); //Open popup on browser window
5) window.confirm('text'); //Open popup on browser window
6) window.prompt('text'); //Open a popup on the browser window with a text field
7) window.location.href = 'url_or_page_name'; //For change location or redirect to another page.
8) document.getElementById('id_name').innerHTML = 'text'

NOTE: * You can also add CSS like -->
document.getElementById('id_name').style.fontSize = '35px';




Some Pre-build commonly used Functions/Events in Javascript/Js:

onclick     => The user clicks an HTML element
ondbclick => The user double-clicks an HTML element
onmouseover => The user moves the mouse over an HTML element
onmouseout => The user moves the mouse away from an HTML element
onkeydown => The user pushes a keyboard key
onload     => The browser has finished loading the page


NOTE: * More HTML DOM Events are present...


IF(){} ELSE{}:
//if()
if('some_condition_here')
{
//execution code
}

//if()...else
if('some_condition_here')
{
//execution code
}
else
{
//execution code
}

//if()...else if()....else if()...else or Nested if/else
if('some_condition_here')
{
//execution code
}
else if('some_condition_here')
{
if('some_condition_here')
{
//execution code
}
else
{
//execution code
}
//execution code
}
else if('some_condition_here')
{
//execution code
}
else
{
//execution code
}



LOOPS:
1) 'for' loop:

for(initialize ; condition ; increment/decrement)
{
//execution code
}
ex:

for(var i=1 ; i <= 5 ; i++)
{
document.write('This is Blog.<br>');
}

OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.

2) 'while' loop:

initialize;
while(condition)
{
//execution code
increment/decrement;
}

ex:
var i=1;
while(i <= 5)
{
document.write('This is Blog.<br>');
i++;
}

OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.


3) 'do{}while' loop:

initialize;
do
{
//execution code
increment/decrement;
}while(condition);
ex:

var i=1;
do
{
document.write('This is Blog.<br>');
i++;
}while(i <= 5);

OUTPUT:
This is Blog.
This is Blog.
This is Blog.
This is Blog.
This is Blog.



NOTE: * Difference between 'while(condition){}' and 'do{}while(condition)' is that, In while first check condition and then execution starts but In do while by default it executes first and then check the condition and execute further.


4) 'for/in' loop:

In Javascript, for/in loop specially used for print/display arrays through properties of objects. It takes an argument as an array -> assign properties in new variable one by one and pass inside the loop or execution part.


for(new_variable (which holds properties) in array_variable)
{
//execution code
}

ex:
var text ='';
var user = {name:"Atul", name:"Singh", age:18};
var prop;
for (prop in user) {
  text += user[prop] + " ";
}
document.getElementById("id_name").innerHTML = text;

OUTPUT:
Atul Singh 18




SWITCH CASE:
'switch' in javascript same as in 'C/C++' programming language.

switch (variable)
{
case 'value1':
//execution code
break;
case 'value2':
//execution code
break;

(optional)
default:
//execution code
break;
  }

  ex:
  var n=3;
  switch(n)
  {
  case 1:
  document.write('This');
  break;

  case 2:
  document.write('is');
  break;

  case 3:
  document.write('Blog');
  break;
  }

  OUTPUT:
  Blog




FUNCTIONS:
Javascript function called when an event occurs such as the mouse hovering or clicking on the button.

function function_name((optional parameters))
{
//function body or execution code
//function can also return value to the caller.
}

ex:
var a = 12;
var b = 14;
swap(a,b);
function swap(a , b)
{
[a, b] = [b, a];
document.write(a+" "+b);
//here function can also return value
}
OUTPUT:
14 12




ARRAYS:
Javascript has Array and String pre-build functions.

1) Indexed array:
The indexed array key starts from '0' and continues with the default key '0, 1, 2, 3, ......so on'. but the type of Indexed array is 'object'.


ex:
var laptop = ['dell','hp','lenovo','acer']; //Initialize array.

document.write(laptop);

OUTPUT:
dell, hp, lenovo, acer



2) Associative array:
An associative array, here we create user define keys such as 'name' and associate them with the ':' colon sign.


ex:
var user = {name: 'Raja', email: 'raja@gmail.com', age: '35'}; //Initialize array.

document.write(user['name']); //For particular property value
var text='';
var prop;
for (prop in user) {
  text += user[prop] + " ";
}
document.getElementById("id_name").innerHTML = text; //For whole array


OUTPUT:
Raja raja@gmail.com 35



Here, Some videos which will show 'How Javascript changes behavior at the run time ?' : 


Javascript Video and JQuery Video




😃 Embrace the joy of coding!

Comments

Popular posts from this blog

JavaScript File Import and Export: A Comprehensive Guide

JavaScript, the language that powers the modern web, has evolved significantly over the years, and its capabilities extend beyond simple script tags in HTML. One of the most important features introduced in ECMAScript 6 (ES6) is the ability to modularize code using import and export statements. This article will dive into JavaScript file import and export, exploring how to effectively organize and share code across multiple files. Understanding Modules: Before ES6, JavaScript needed more built-in support for modules, making it challenging to manage large codebases. ES6 introduced the concept of modules, which allow developers to split their code into reusable and manageable chunks. Modules facilitate better code organization, encapsulation, and the reduction of global scope pollution. Exporting from a Module: In JavaScript, you can export variables, functions, classes, or even objects from a module to be used in other files. The export keyword is used to mark items for export. For exam...

Understanding Asynchronous JavaScript: Exploring async/await, Promises, and Callbacks

  Asynchronous programming is a fundamental aspect of JavaScript that allows you to execute code without blocking the main execution thread. It enables tasks like fetching data from APIs, reading files, or handling user interactions to be executed without freezing the entire application. In this article, we'll dive into the concepts of async/await, Promises, and callbacks – powerful tools that make managing asynchronous operations more elegant and efficient. Callbacks: The Traditional Approach Callbacks are the foundation of asynchronous programming in JavaScript. A callback is a function that is passed as an argument to another function. It's executed after the completion of an asynchronous operation. However, using callbacks can lead to callback hell – a situation where nested callbacks become hard to manage and read. Example: function fetchData(callback) {   setTimeout(() => {     const data = 'Hello, world!';     callback(data);   }, 1000); } fe...

Understanding JavaScript Variables: var, let, and const Explained

  In the dynamic world of JavaScript, the way you declare and use variables can greatly impact your code's behavior and performance. With the introduction of ES6 (ECMAScript 2015), JavaScript developers gained more flexibility and control over variable declarations through the use of three keywords: var, let, and const. In this blog, we'll dive into the differences between these keywords and explore when to use each one. Understanding var, let, and const: var :  The Old Way The var keyword was the traditional way to declare variables in JavaScript. However, it has some quirks that can lead to unexpected behaviors. Variables declared with var are function-scoped, meaning they are accessible within the function where they are declared or globally if declared outside of a function. This scope behavior often caused issues in complex codebases. let :  The Block-Scope Hero ES6 introduced the let keyword to address the scoping issues of var. Variables declared with let are block...