Basics in Javascript: Javascript is a scripting language used frequently to add interaction and animation to web pages. Most large companies like Facebook, amazon, and others use Javascript to make their web pages more functional and interactive. It is mainly used for front-end web development tasks. Javascript is a major component of HTML and CSS on a web page. Let us learn more about the Basics of Javascript.
Basics in Javascript: An Introduction
Javascript is a versatile, beginner-friendly, client-side scripting language used for implementing extra functionalities to web pages to make them more dynamic and interactive. It consists of standard built-in objects and predefined methods.
Javascript is an object-oriented programming (OOPs) language. Its syntax resembles much of C and Java. Let us know some of the reasons why Javascript is a better tool than the others on the market.
Highlights:
- Introduction to Javascript: The content introduces Javascript as a versatile, client-side scripting language used for adding interactivity to web pages. It emphasizes its role in making web pages dynamic and interactive, highlighting its standard built-in objects and predefined methods.
- Importance of Learning Javascript: It explains why learning Javascript is essential, especially for individuals interested in web development. Javascript is portrayed as a major language for creating user-friendly and dynamic web pages, with its significance underscored by its use in major companies like Google, Facebook, and Amazon.
- Hello World in Javascript: The content provides a step-by-step guide on how to write the classic “Hello World” program in Javascript. It covers creating a .js file, linking it to an HTML file, and using Javascript to manipulate HTML elements to display “Hello World” on a web page.
- Manipulating HTML with Javascript: It discusses various methods for selecting and manipulating HTML elements using Javascript. Methods such as getElementById, getElementByClassName, getElementsByTagName, and querySelector are explained, highlighting their usage in accessing and modifying HTML elements.
- Variable Declaration and Data Types: The content explains different ways to declare variables in Javascript using var, let, and const keywords. It also covers various data types supported by Javascript, including numbers, strings, arrays, functions, booleans, objects, dates, null, and undefined.
Basics in Javascript: Why learn Javascript?
Javascript is a major language used in web development for creating dynamic and user-friendly web pages. It is one of the three important pillars of web development. If you are someone who is learning web development, then Javascript is crucial for making your web page active and working.
Javascript is used to determine and implement the behaviour of web pages. It was first introduced in 1995 by Brendan Eich. It was aimed to adding interactions to a website and add more user-friendly functionalities. Javascript is crucial to making your website more functional and interactive. Nowadays, Javascript is used by major companies like Google, Facebook, Amazon, etc.
Basics in Javascript: Hello World
Let us know how to write our first program using Javascript in the table below.
- Create a file name with the extension .js and save it.
- Now, go to your index.html file and enter the code given below inside the <body> tag. You can use this code just before closing <body> tag.
<script src=”script/main.js”></script> |
- Now, you also need to link the main.js file in your CSS using the <link> element. Now, let us print “Hello World” using the code given below. The ‘querySelector()’ is used to select an element of HTML and make changes as per requirement.
const helloWorld = document.querySelector(“h1”);
helloWorld.textContent = “Hello World”; |
- Load the index.html file in your browser, and then you will be able to see Hello World on your screen.
Basic in Javascript: Select and Manipulate HTML
There are various methods available in Javascript that can help to modify and access HTML elements in the Document Object Model (DOM). These are some of the frequently used Javascript selectors. Check some of the methods to select an element in Javascript.
- getElementsById: This is used to select an element using its ID number. The ID number in an HTML document is unique.
var element = document.getElementById(“ID1”); |
- getElementByClassName: In Javascript, elements can be selected using their ClassName. It returns a list of nodes.
var element = document.getElementByClassName(“className”); |
- getElementsByTagName: We can also use a Tag name in HTML elements to select an element from the HTML document.
- querySelector: It is used to select the first element in the selector. For Id, we use # and for className, we use a ‘dot’ in the bracket.
var element = document.querySelector(“.className1”); |
Many more selectors can take a name, parentNode, children node, etc, to select the specific element.
Basic in Javascript: Declaring Variable
There are three major methods to declare variables in Javascript check them below.
1. var keyword
The var keyword in Javascript is used to declare global object variables. It can be used when a local variable is declared and initialized in the same statement. When we declare a variable with the ‘var’ keyword, then we can easily update as well as re-declare variables within their scope.
var myVariable = “Hello, World!”; |
2. let Keyword
The ‘let’ keyword is a block-scoped method of declaring a variable in Javascript. When a variable is declared using the ‘let’ keyword then it can be updated but can’t be redeclared. It can only be used inside a block where they are defined.
if (true) {
let myVariable = “ This article is provided by PW Skills”; Console.log (myVariable); //Output: This article is provided by PW Skills } console.log(myVariable); // It will throw an error as let does not allow access outside the block where variables have been declared. |
3. const keyword
The ‘const’ keyword is used to assign a value that cannot be reassigned after feeding a value inside. Also, it is block-scoped. Hence, we cannot access it outside a given scope.
const myVariable = “Hello, World!”; |
You can retrieve the value of a variable by calling its assigned name.
Basic in Javascript: Different Data Types
Javascript supports variables that can hold different data types. Some of the supported data types are mentioned here.
Basic in Javascript: Data Types | ||
Data type | Description | Example |
Number | Numbers are simple numerical values that are not assigned using single or double quotation marks. | let var = 99; |
String | The sequence of characters arranged together is called a string. It is always enclosed inside a double or single quotation mark | let str = ‘Physics Wallah”;
let str2 = “PWSkills”; |
Array | In Javascript, an array is used to store multiple values in a single variable. Elements stored inside an array can be accessed using their index. | let arr = [ 1, ‘pwskills’, ‘Ankit’, 21]; |
Function | It is used to declare a function using Javascript. Its keyword is ‘function’. | function helloWorld(name){
console.log(“Hello, “ + name + “!”); |
Boolean | Boolean values are used to find an answer in two forms: true and false. | let isTrue = true;
If (isTrue){
console.log(“True”)
else{
console.log(“False”)
} |
Object | In javascript, data can be presented in the form of key-value pairs | var person = {name: “ABC”, age: 18, rollNo: 21}; |
Date | It consists of date and time. | var currDate = new Date(); |
Null | It represents the absence of any value inside the variable. | var nullValue = null; |
undefined | It is used to represent an uninitialized function without a return value. | var undefinedVar; |
Basic in Javascript: How to add Comments
Javascript support two types of comments, single-line and multi-line comments. Comments are very useful when we want to explain a particular segment of code and its function to make it more readable. The compiler ignores any statements inside these comments and does not execute them.
- Single-line comments are represented by twp forward slashes ‘//’. It is generally used for quick explanation in a single line.
- Multi-line comments are closed with a forward slash followed by an asterisk ‘/*’ and are closed by a ‘*/’ asterisk followed by a forward slash.
Basic in Javascript: Operators
Javascript supports various operators such as assignment, comparison, bitwise, string, bitwise, and more. Let us check the list of operators supported by Javascript below.
Basic of Programming in Java: Operators in Java | ||
Arithmetic Operator in Java | ||
Operator | Description | Example |
+(Addition) | It is used to add two or more values. | let x = 4;
let y = 2;
let z = x + y;
//output 6 |
-(Subtraction) | It is used to subtract two or more values. | let x = 4;
let y = 2;
let z = x – y;
//output 2 |
*(Multiplication) | It is used to multiply two values on either side of the operator. | let x = 4;
let y = 2;
let z = x *y;
//output 8 |
/(Division) | It is used to divide the left hand operator by right-hand operator | let x = 4;
let y = 2;
let z = x/ y;
//output 2 |
%(Modulus) | It returns the remainder when the left-hand operator is divided with the right-hand operator. | let x = 4;
let y = 2;
let z = x%y;
//output 0 |
Assignment Operator in Java | ||
= | It assigns the value to a left-side operand from a right-side operand. | let x = 10
//Assigns 10 to the variable x |
+= | It keeps on adding the right operator to the left operand and assigning the result obtained to the left operand. | let a = 22
let b = 12
a +=b;
//output a = 34, b = 12 |
-= | It subtracts the right-hand operand from the left-hand operator and assigns the value to the left operator. | let a = 22
let b = 12
a -=b;
//output a = 10, b = 12 |
*= | It is used to multiply the value in the right hand to the left-hand operand. | let a = 2
let b = 2
a *=b;
//output a = 4, b = 2 |
/= | It takes the division of the two operands and then assigns the result to the left operand. | let a = 2
let b = 2
a /=b;
//output a = 1, b = 2 |
%= | It takes the modules and assigns the remainder value at the left-hand operand. | a %= b, it is the same as a= a%b |
^= | It is used to perform exponential calculation and assign the calculated value to the left-hand operand. | a^=b |
Relational Operators in Java | ||
== | It checks whether the left-hand and right-hand operands are equal. | let a = 14
let b = 11
a == b is not true. |
!= | It checks whether the left-hand and right-hand operands are not equal. | let a = 14
let b = 11
a!= b is true. |
> | If the value of the left operand is greater than the right-hand operand, then it returns true. | let a = 14
let b = 11
a > b is true. |
< | If the value on the left-hand side is smaller than the right-hand side, then it returns true. | let a = 14
let b = 11
a < b is false. |
>= | It tells the left side value is greater or equal to the right-hand side. | let a = 14
let b = 11
a >=b is true. |
<= | It tells the left value is smaller or equal to the right-hand side. | let a = 4
let b = 6
a <=b is true. |
Logical Operators in Java | ||
&& (and) | It will return true only if both the operands are true. | a = 4
a<9 && a<10 will return true. |
|| (OR) | It will return true if any of the operands on either side are true. | a = 11
a<10 || a<12 |
! (NOT) | It returns true when both the operands are false. It is also used to negate the value of a variable. | a = true
!a, it will return false |
++ | It increments the value of a variable by 1. | a = 1
a++ Now, it will return a = 2 |
– | It will decrement the value of a variable by 1 | a = 5
a– Now, it will return a = 4 |
Basic in Javascript: Conditionals
Conditional statement is used in javascript to determine whether or not a given piece of code will run. There can be different types of conditional statements in Javascript. ‘If and else’ statements are frequently used in Javascript where the block will be executed if a condition is true. But if the statement is not true then the else block is executed.
Basic in Javascript |
if(10>2){
var result = “If block Success.”; } else{ var result = “If block fails.”; } |
These conditional statements can be used in many variations such as If else, else, else if, and more. Let us check an example of else if statement in Javascript.
Basic in Javascript |
let num =10;
if (num>10){ console.log(“The number is greater than 10.”); else if ( num<10){ console.log(“The number is lesser than 10”); else { console.log(“The number is equal to 10”); } |
Basic in Javascript: Functions
Functions in Javascript are reusable block of code which can be used repeatedly for executing a specific task. In Java, functions are declared using ‘function’ keyword. Let us understand the function using a simple example.
Basic in Javascript |
// Function declaration
function greetings(name) { console.log(“Hello, ” + name + “!”); } // Function call greet(“Ankit”); // Output: Hello, Ankit! |
Arrow functions are used in Javascript based on ES6+ to make the code syntax concise and implicit return.
Basic in Javascript: Events
Events are generally actions that are implemented based on various interactions of a user with the system such as mouseover, mouseout, click, key down, keyup, submit, resize, etc. Event handling is carried out in Javascript using event handlers which are implemented in response to specific events being triggered.
Basic in Javascript |
<button id=”myButton”>Click me</button> //button
<script> // Function used to handle clicks. function handleClick() { alert(“Button clicked!”); } // Adding event listener for click and function to handle clicks. document.getElementById(“myButton”).addEventListener(“click”, handleClick); </script> |
Check the example below, it shows a button that consists of an event handler ‘alert’ which will be activated when a user clicks on the button.
Learn Javascript with PW Skills
Join our Full Stack Web Development Course to learn various aspects of web development. Land a career as a web developer with our industry-level experts guiding you throughout the course. Our course provides the best value at a very affordable course. This course also provides 100% placement assistance and industry-recognized completion certificates. Hurry! and grab some exciting offers only at @pwskills.com
Basic in Javascript FAQs
What is a basic tag in Javascript?
The tag is the basic tag in Javascript. It is used to contain scripting statements or external scripts.
What are some uses of Javascript?
Javascript is generally preferred for front-end web development as it is a scripting language. It is used frequently for image manipulation, dynamic changes, form validation, etc.
Why is Javascript the best?
Javascript is a scripting language that is frequently used to create flexible user-friendly front-end designs. It is versatile, reliable, and provides faster execution.