Skip to content

Subhajit-Bera/JavaScript-for-Beginners

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

86 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Script

JavaScript was invented by Brendan Eich in 1995.

What is JavaScript?

JavaScript is a dynamic programming language that's used for web development, in web applications, for game development, and lots more. It allows client-side scripts to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

If we want to perform any sequence of steps,calculation or implement any algorithm then we use JavaScript to do that.

What can JavaScript do?

  • JavaScript can add new HTML and change existing HTML from DOM.
  • It can even react to any events (actions).[Response from server,keyboard press,mouse movement]
  • It can also manage the AJAX requests (GET or POST request). Ajax Request: Asynchronous JavaScript And XML used to change the content of a page dynamically without reloading it.
  • JavaScript can get and set cookies and use local storage.

What Can’t In-Browser JavaScript Do?

  • JavaScript cannot read or write to and from computer hard disk without user permissions.
  • The browser does not allow the JavaScript of any website to collect the AJAX information of the other website because it generates the error of the same origin policy.
  • To summarize, JavaScript can only access the permitted resources but cannot access your documents on personal computers. These strict policies are developed to make sure that your computer is safe.

What Makes JavaScript a Unique language?

  • The most important thing that makes it a unique language is, it has a complete integration of HTML and CSS. They provide it with a lot of extra support.
  • Also it provides the use of simple APIs (Application Programming Interface).
  • It also supports the major modern browsers which are enabled by default. If you turn off the feature of JavaScript in the browser, you cannot access any website.

WHAT IS DOM ?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript.

For example, the DOM specifies that the querySelectorAll method in this code snippet must return a list of all the

elements in the document

Variables In Java Script

Java is a dynamic type language. Means we don’t need to specify the data type. The set of types in the JavaScript language consists of primitive values and objects.

1.Primitive Values(All types except objects define immutable values)

  • Boolean type
  • Null type
  • Undefined type
  • Number type
  • BigInt type
  • String type
  • Symbol type

typeof and type conversion is explaind in source code.

Code reference

String In Java

A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. Strings in JavaScript are primitive data types and immutable, which means they are unchanging.

Defining a String:

We can define a string in JS by using “ ” and ‘ ‘ both. When we need to use “ “ inside a string we define the string using ‘ ‘ and vice versa. 1

String Template Literals :

2

String Functions

1.Length function :

Length is an ECMAScript(ES1) feature. Used to return the length of an object.

3

2.indexOf(“”) and lastIndexOf(“”) :

4

3.slice(start index,end index): perform slicing from starting index to end-1 index.

5

4.substring(start index,end index): works the same as slice.

6

ONLY DIFFERENCE BETWEEN slice AND substring IS: slice TAKES NEGATIVE VALUE ,WHERE substring DOESN’T ALLOW NEGATIVE VALUE.

5.substr(start index,length/no of character needed) : get the substrig from starting index to no of character (including start index->total 6)

7

6.replace:

8

7.toUpperCase() & toLowerCase()

10

8.charAt() & charAt()

11

9.concat(“new string”):

12

10.trim()

13

11.Another way to access character from a string:

14

Code reference

Operators:

image

== vs ===

== only check values
=== check values as well as data type
ex:
if(12=='12') -> true
if(12==='12') ->false

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true.
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

if-else statement:

20

switch-case statement:

21

Objects In JavaScript

The object class represents one of JavaScript’s data types. It is used to store data in the form of key and value pairs.

15

In this above example we create object student manually.

Accessing values of an Object:

16

If we want to create a key using more than one word(using space inside a name) then we need to put the key name inside a double quotation “ ”. Otherwise it will give an error.

17

If we want to access the value of “student 2” then we have to use the 2nd method of accessing otherwise it will give syntax errors.

18

code reference

Adding new data in object:

image

Array In JavaScript

Array is a special type of object. In JavaScript arrays can contain various types of data together.

Defining An Array :

19

Creating array using new keyword:

22

Creating An Empty Array of Specific number of Blocks(Array of Undefined elements):

23

Length of An Array:

24

Accessing Array Elements:

25

Add An Element In the End of Array:

26

Delete element from anywhere -> splice(start index, length)

image

image

slice(start index,end index) -> return a new array (start->end-1)

image

includes

image

Sort An Array:

27

code reference

Functions in Java Script

A JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when "something" invokes it (calls it).

  • A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
  • Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
  • The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
  • The code to be executed, by the function, is placed inside curly brackets: {}

Function Syntax :

28

Creating a Function:

29

This function would get executed when someone calls or invokes it.

Calling the Function:

30

Function bill doesn’t return anything.

Lets see a function which returns some value :

31

Default Parameters:

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed. 32

If we do not pass the value of y, in that case the default value of parameter y will be taken. 33

code reference

Anonymous Function:

image

Scoping

var vs let vs const

var: Scope of var is by default global.Doesn’t give any error if we declare a variable multiple times (same name). Which may lead to a problem in a program. But if we declare the var inside any function, then its scope will remain under that function. image

let : We can’t declare a variable multiple times using let(unless it is declare inside a block or function).If we declare it inside any function or block, then its scope will remain under that function or block.It is preferred to use let upon var.
1 image

2 image

3 image

4 image

5 image

const : Value can’t change once declared.
image

image

Alert, Prompt, Confirm

alert() :

  • The alert() method displays an alert box with a specified message and an OK button.
  • It is often used to make sure information comes through to the user.
  • The alert box takes the focus away from the current window and forces the browser and forces the browser to read the message.
  • Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.
  • alert() doesn’t return anything.

Syntax:

34

Output:

36

prompt():

  • The prompt() method displays a dialog box that prompts the user for input.
  • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed.
  • The prompt() method returns the input value if the user clicks "OK", otherwise it returns null.
  • Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.
  • propt() bt default value is String , if we want to take a number as input then we have to perform type converstion:

    let num=Number(prompt("Enter a number"));

Syntax:

35

Output:

37

prompt() with default argument:

Here Guest is the default argument.

38

Output:

40

Many browsers (i.e:Internet Explorer) do not allow prompt() without default argument. In that case at least add “” if you do not want any default value.

39

confirm():

  • The confirm() method displays a dialog box with a message, an OK button, and a Cancel button.
  • A confirm box is often used if you want the user to verify or accept something.
  • A confirm box takes the focus away from the current window, and forces the user to read the message.
  • Do not overuse this method. It prevents the user from accessing other parts of the page until the box is closed.
  • The confirm() method returns true if the user clicked "OK", otherwise false.

Syntax:

41

Output :

42

Example of using confirm() in code:

43

code reference

Loops

Loops can execute a block of code a number of times. In order to run the same code over and over again, each time with a different value, loops are more preferable.

for Loop:

For loop ,loops through a block of code a number of times.

Syntax:

44

  • Expression 1 is executed (one time) before the execution of the code block.
  • Expression 2 defines the condition for executing the code block.
  • Expression 3 is executed (every time) after the code block has been executed.

Code:

45

Output:

46

forEach() Loop:

The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

Syntax:

47

  • function() :A function to run for each array element.
  • currentElement : The value of the current element.

Code:

48

Output:

49

Code 2:

Defining function separately and then use that with forEach() loop: 50

Output:

49

Function with multiple parameters in forEach loop:

51

Output:

52

for of Loop:

The JavaScript for of statement loops through the values of an iterable object. It loops over iterable data structures such as Arrays, Strings, Maps, NodeLists and many more.

Syntax:

53

Code:

54

Output :

55

for in Loop:

The JavaScript for in statement loops through the properties of an Object.

Syntax:

56

Code:

57

Output:

58

while Loop:

The while loop loops through a block of code as long as a specified condition is true.

Syntax:

59

Code:

61

do while Loop:

The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax:

62

Code:

63

Output:

do while loop at least run one time. That’s why its printing “34 is less than 30 and we are inside do while loop” one time. 64

code reference

Three ways to add JavaScript :

1.Inline Js:

65

2.Internal JS:

66

3.External JS:

67

DOM (Document Object Model)

What is DOM ?

The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page.

Why is the DOM necessary?

Until now our websites have been static If we want our web site to be interactive, then we need to be able to change parts of the web site on the fly.So that means, when a user clicks on a button, we'll need to respond to that by changing the content or the appearance of our website. But once our web site is live on the Internet, we can't sit there and wait for the user to click on things on our web site and then update the HTML and CSS code, and then reload their web page.That's impossible.

Now this is the problem that the DOM or the Document Object Model solves. It basically catalogs the web page into individual objects that we can select and manipulate.

How does DOM work?

The task of converting an HTML file into the DOM is done by the browser when you load up the web page. And what it does is that it turns each of these elements and their associated data into a tree structure with a whole bunch of objects that you can select and manipulate.

The tree model on the below is usually how the DOM is represented.

image

Accessing body using DOM image

Accessing head using DOM image

Accessing whole html using DOM image

Here it showing text->which basically refers the space between body and it's first div element image

Accessing first div present inside using DOM image

Accessing element using id and class name image

..........

Window Object

The window object represents a window in browser.Window is the object of browser.It is not the object of javascript.An object of window is created automatically by the browser.The javascript objects are string, array, date etc.

Methods of Window Object

Some of the frequently used window object methods are :

  • alert() : Displays an alert box with a message and an OK button.
  • prompt() : Displays a dialog box to get input from the user.
  • confirm() : Displays a dialog box with a message and an OK and a Cancel button.
  • open() : Used to open a new window.
  • close() : Close the current window.
  • setTimeout() : Calls a function or evaluates an expression after a specified number of milliseconds.
  • clearTimeout() : Clears a timer set with setTimeout().
  • setInterval() : Calls a function or evaluates an expression at specified intervals of milliseconds.
  • clearInterval() : Clears a timer set with setInterval().

We have already seen about alert(),prompt() and confirm() in detail. Let's explore about other methods in detail :

setTimeout() : This method calls and run a function once after a specified number of milliseconds.

Syntax: setTimeout(function name,time in ms);

Code:

68

Output: (After 5000 milliseconds)

69

We can pass multiple argument to the function and use it with setTimeout():

70

Output: (After 5000 milliseconds)

71

clearTimeout():This method clears a timer set with the setTimeout() method.

If a user visits our website and we want to ask a user to sign up after 10 seconds but the user already signed up before 10 seconds ,for this type of scenario we can use clearTimeout() to clear the timer set with the setTimeout() method.

To clear a timeout, we use the id returned from setTimeout().Because of that function associated with setTimeout() method will not run.

Syntax: clearTimeout(id returned by setTimeout());

Code:

72

Output: It prints the id returned from setTimeout()

73

setInterval() : Calls a function or evaluates an expression at specified intervals of milliseconds.The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

If we want to execute a function multiple times and at a specific interval of time then ,it is preferable to use setInterval() instead of setTimeout().

Syntax: setInterval(function name,time in ms);

Code:

74

Output:

75

fun3 runs 17 times and it will keep running until clearInterval() is called, or the window is closed.

clearInterval() : Clears a timer set with setInterval().

To clear an interval, we use the id returned from setInterval() method.

Syntax: clearInterval(id returned by setInterval());

Code:

76

Output: It prints the id returned from setInterval()

77

code reference

Creating a basic Real Time Clock with setInterval() method:

Code:

78

Bowser Window:

79

code reference

Date and Time in JavaScript

Java Script has a built-in Date object.It stores the date, time and provides methods to get and set day, month, year, hour, minute and seconds.Date objects are static.

###Creating Date Object: Date objects are created with the new Date() constructor. 80 Creating a Date object without arguments shows the current date and time.

Output :

81

Diffrent ways to create a new date object through passing arguments:

  • new Date(date string)
  • new Date(year,month)
  • new Date(year,month,day)
  • new Date(year,month,day,hours)
  • new Date(year,month,day,hours,minutes)
  • new Date(year,month,day,hours,minutes,seconds)
  • new Date(year,month,day,hours,minutes,seconds,ms)
  • new Date(milliseconds)

JavaScript counts months from 0 to 11.
0: January
11: December

Create Date Objects with date string:

82

Output:

83

Create Date object with year,month,day,hours,minutes,seconds,ms:

84

Output:

85

Get Date Methods in JavaScript

From Date object,we can easily get the current date and time with the help of Get Date methods.

Code:

86

Output:

87

Set Date Methods in JavaScript

Set Date methods allow us to set date values of a Date Object i.e : years, months, days, hours, minutes, seconds, milliseconds .

Code:

88

Output:

89

code reference

Arrow Function in JavaScript

An arrow function expression is a syntactically compact alternative to a regular function expression,although without its own bindings to this, arguments, super or new.target keywords. Arrow function expressions are ill-suited as methods, and they cannot be used as constructors.

90

Output:

91

Arrow Function with one argument and one statement :

  • If the arrow function has one argument ,we don't have to put brackets.
  • If the function has only one statement, we can remove the brackets and the return keyword.

92

Output:

93

Arrow function as Expression:

94

Output:

95

Arrow function with multiple line:

96

Output:

97

Lexical this in Arrow Function:

Incase of a regular function , this keyword has its scope inside the function where it calls. Means it refers to the variable inside the function where it is called. But arrow function does not have its own this.Incase of arrow function this keyword always represents the object that defined the arrow function.

About

We are trying to cover basic JavaScript topics for beginner

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors