What is JavaScript?
If HTML is the structure of the body and CSS is like skin then JavaScript is like the brain of a webpage. It adds interactive elements like animations, popups, and scrolling videos in a webpage.
How to link JS?
- Inline JavaScript: You can include JavaScript code directly within your HTML file using the
<script>
tag. Place the<script>
tag within the<head>
or<body>
section of your HTML document. Here's an example:
<script type="text/javascript"> //code goes here. </script>
- External JavaScript File: You can also link an external JavaScript file to your HTML document using the
<script>
tag with thesrc
attribute. Thesrc
attribute specifies the path to the JavaScript file. Here's an example:
<script src="script.js"></script>
Variables and Data Types
- Variables: In JavaScript, variables are declared using the
let
,const
, orvar
keyword.let
andconst
are block-scoped, whilevar
is function-scoped. Code example of Declairing Variables:
let Lecturely; const url = 'www.lecturely.com';
- Data Types: JavaScript has several primitive data types, including
number
for numeric values,string
for text,boolean
for true/false values,null
for intentional absence of any object value, andundefined
for uninitialized variables. It also has complex data types likeobject
for storing collections of key-value pairs andarray
for storing multiple values in a single variable. Additionally, functions are a special type of object in JavaScript.
Operators
- Arithmetic Operators: These operators perform mathematical calculations, such as addition (
+
), subtraction (-
), multiplication (*
), division (/
), and modulus (%
). - Assignment Operators: These operators assign values to variables. For example,
=
assigns a value, while+=
,-=
,*=
,/=
, and%=
perform a calculation and assign the result to the variable. - Comparison Operators: These operators compare two values and return a boolean result. They include strict equality (
===
), strict inequality (!==
), greater than (>
), less than (<
), greater than or equal to (>=
), and less than or equal to (<=
). - Logical Operators: These operators are used to combine or negate boolean values. The logical AND (
&&
), logical OR (||
), and logical NOT (!
) operators are commonly used.
Code example:
let x = 10; let y = 5; let sum = x + y; // Addition let isGreater = x > y; // Comparison let result = (x === 10) ? 'x is 10' : 'x is not 10'; // Ternary operator
Control Flow
- Conditional Statements:
if
,else if
, andelse
statements are used to execute different blocks of code based on specified conditions. - Ternary Operator: It provides a concise way to write conditional statements in a single line. The syntax is:
condition ? expression1 : expression2
If the condition is true, expression1 is executed; otherwise, expression2 is executed. - Switch Statement: It evaluates an expression and executes code blocks based on different cases. Each case is defined using the
case
keyword, and the code block for a matching case is executed. - Looping Statements:
for
,while
,do...while
,for...in
, andfor...of
loops are used to repeat blocks of code based on different conditions. - Loop Control Statements:
break
is used to exit a loop, whilecontinue
skips the current iteration and proceeds to the next iteration.
Code example:
let age = 18; if (age >= 18) { console.log('You are an adult.'); // Condition is true } else if (age >= 13) { console.log('You are a teenager.'); } else { console.log('You are a child.'); } let i = 0; while (i < 5) { console.log('Iteration:', i); i++; } for (let j = 0; j < 5; j++) { console.log('Iteration:', j); }
Functions
- Function Declaration: Functions are declared using the
function
keyword followed by the function name, optional parameters enclosed in parentheses, and the code block to be executed. - Function Expression: Functions can also be assigned to variables using function expressions. They don't require a function name and are useful for anonymous or callback functions.
- Arrow Functions: Arrow functions provide a concise syntax for writing functions. They use the
=>
arrow notation and are particularly useful for shorter functions.
Code example:
function greet(name) { console.log('Hello, ' + name + '!'); } greet('Lecturely'); // Function call with argument const multiply = (a, b) => a * b; // Arrow function console.log(multiply(5, 3));
Arrays
- Creating Arrays: Arrays are created using square brackets
[]
and can store multiple values of any type. Arrays can be assigned to variables using theconst
keyword. - Accessing Elements: Array elements are accessed using their index within square brackets. The index starts from 0 for the first element.
- Array Methods: Arrays have built-in methods like
push()
,pop()
,shift()
,unshift()
,slice()
,splice()
,forEach()
,map()
,filter()
, andreduce()
for manipulating and iterating over array elements.
Code example:
const numbers = [1, 2, 3, 4, 5]; console.log(numbers.length); // Length of the array console.log(numbers[0]); // Accessing array element numbers.push(6); // Adding an element to the end of the array console.log(numbers); const squaredNumbers = numbers.map(num => num ** 2); // Mapping each element to its square console.log(squaredNumbers);
Objects
- Creating Objects: Objects are created using curly braces
{}
and consist of key-value pairs. Keys are strings that act as property names, and values can be of any data type. - Accessing Object Properties: Object properties are accessed using dot notation (
object.key
) or square bracket notation (object['key']
). - Object Methods: JavaScript provides built-in methods like
Object.keys()
,Object.values()
, andObject.entries()
to work with objects.Code example
const person = { name: 'John', age: 30, profession: 'Developer' }; console.log(person.name); // Accessing object property console.log(Object.keys(person)); // Getting object keys as an array const keys = Object.keys(person); for (let key of keys) { console.log(key + ':', person[key]); // Accessing object properties dynamically }
DOM Manipulation
- Selecting Elements: The
document.querySelector()
method selects the first element that matches a specified CSS selector, whiledocument.querySelectorAll()
selects all matching elements. - Modifying Elements: DOM elements can be modified using properties like
.innerHTML
to set or retrieve the HTML content,.textContent
to set or retrieve the text content,.setAttribute()
to set attributes, and.addEventListener()
to attach event listeners to elements.Code example:
const element = document.querySelector('#myElement'); element.innerHTML = 'Hello, Lecturely!'; // Modifying element content const button = document.querySelector('#myButton'); button.addEventListener('click', () => { console.log('Button clicked!'); // Event listener for button click });
Error Handling
- Try-Catch Blocks: These blocks are used to handle potential errors. Code that might throw an error is placed in the
try
block, and if an error occurs, it is caught in thecatch
block where appropriate actions can be taken.Code example:
try { // Code that may throw an error const result = x / y; console.log(result); } catch (error) { console.log('An error occurred:', error.message); // Handling and displaying the error message }
Variables
Var - The most common variable. This tells JS you’re declaring a variable.
Const – A variable that can never be reassigned and is not accessible before they appear within the code.
Let - A variable can be reassigned but not re-declared.
var age = 23 - numbers.
var x - variables.
var a = “init” - Text(strings)
var b = 1+2+3 - Operations.
var c = true - True & False Statements.
var name = {
fistName = “Lecture”,
lastName = “ly”
}
Concat() – Join multiple arrays into one.
indexOf() – Returns the very first position at which a given element appears in an array.
join() – Combines element of an array into one single string and then it will return a string.
lastIndexOf() – Gives the last position at which an element appears in an array.
pop() – Removes the last element of an array.
push() – Adds a new element in the end.
reverse() – Reverse the order in an array.
shift() – Removes the first element of an array.
sort() – Sorts elements alphabetically.
splice() – Adds elements in a specified way and position.
toString() – converts elements into the string.
unshift() – Adds a new element to the beginning.
valueOf() – Returns the primitive value of the object.
Operators
These can be single OR multiple data values used to produce result, including basic operators, Comparison Operators etc.
Sign/Symbol | Name of Sign/Symbol |
---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
(...) |
Grouping Operator |
% |
Remainder. |
++ |
Increment Number |
-- |
Decrement Number |
== |
Equal to |
=== |
Equal Value & Equal Type |
!= |
Not Equal |
!== |
Not Equal value or not equal type |
> |
Greater Than |
< |
Less Than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
? |
Ternary operator |
&& |
Logical AND |
!! |
Logical OR |
! |
Logical NOT |
& |
AND statement |
| |
OR Statement |
~ |
NOT |
^ |
XOR |
<< |
Left shift |
>> |
Right shift |
Functions
alert() – An alert box will appear in the browser.
confirm() – Displays a message box with ok/cancel options.
console.log() – Writes information in browser.
document.write() – Write directly to the HTML document.
prompt() – A pop up box appears that will need the user input.
decodeURl() - Decodes a URL created by encodeURI.
decodeURIComponent() – Decodes a URI component.
encodeURI() – Encodes a URI into UTF-8.
encodeURIComponent() – Encodes a URI using numbers to represent letters.
Loops
This will run until it meets certain condition.
for – A very common way to create a loop in JS.
while – This sets up certain conditions for the loop.
do-while – This checks one more time to see if conditions are met.
break – Stops the loop if conditions aren’t met.
continue – Skips the part of loop where certain conditions are met.
Strings
These store text and include escape characters and string methods.
/’ – String.
\’’ – Double Quote.
\\ - Backslash.
\b – Backspace
\f – Form Feed.
\n – Newline.
\r – Carriage Return
\t – Horizontal Tabulator
\v – Vertical Tabulator
charAt() – Returns a character at a position.
charCodeAt() – Provides you the Unicode of character at a specified Position.
concat() – Joins multiple strings together in one.
indexOf() – Returns the position of first occurrence of a element.
lastIndexOf() – Returns the position of last occurrence of an element.
match() – Returns any matches of a particular string.
replace() – Finds and replaces the text.
search() – Finds the text and returns its position.
slice() – Extracts a part of string.
Split() – Divides a string into substring and returns it at a particular position.
toLowerCase() – Converts to lowercase.
toUpperCase() – Convert to uppercase.
valueOf() – Returns the primitive value.
Numbers & Maths
This includes number properties, and methods.
MAX_VALUE – The maximum numeric value.
MAX_VALUE – Smallest positive numeric value.
NaN – Not-a-number.
NEGATIVE_INFINITY – Negative infinity value.
POSITIVE_INFINITY – Positive Infinity Value.
toExponential() – Returns string of a num with specified number of decimals.
toString() – String of a number.
valueOf() – Returns a number as a number.
E – Euler’s number.
LN2 – Natural Logarithm of 2.
LN10 – Natural Logarithm of 10.
LOG2E – Base 2 Logarithm of E.
LOG10E – Base 10 Logarithm of 10.
PI – Number PI.
SQRT1_2 – Square root of ½.
SQRT2 – Square Root of 2.
abs(x) – Returns the absolute (positive) value of x.
Dates
This includes points in time which includes dates, and set part of time.
tan(x) – The tangent of an angle.
Date() – This creates a date object with current date & time.
Date(“2021-09-23”) – Date Declaration as a string.
getDate() – Get the day of the month as a number ranging from(1-31)
getDay() – Weekday as a number (0-6)
getFullYear() – Chooses year as a four digit number as (yyyy).
getHours() – Get the hour ranging from (0-23)
getMilliSeconds() – The millisecond (0-999)
getMinutes() – Gets the minute ranging from (0-59).
getMonth() – Gets the month ranging from (0-11).
getSeconds() – Gets the second ranging from (0-59).
getSecond() – Gets the second ranging from (0-59)
setDate() – Set the day as a number ranging from (1-31)
setFullYear() – Sets the year (optionally month and day).
setHours() – Sets the hour ranging from (0-23)
setMilliSeconds() – Set milliseconds ranging from (0-999).
setMinutes() – Sets the seconds ranging from (0-59).
setMonth() – Sets the month ranging from (0-11)
setSeconds() – Sets the seconds ranging from (0-59)
DOM Node
This DOM allows JS to update the web page and include node properties, methods and element methods.
getElementById() – Selects an single element within the document using specific Id.
querySelector() – This Uses CSS selector to select the very first matching element available in the document.
getElementByClassName() – This allows you to select all the elements with a given class attribute.
getElementsByTagName() – This allows you to locate all elements that matches a given tag name.
querySelectorAll() – Uses CSS selector to select one or more elements.
parentNode – This helps you locate the parent element of an initial selection.
nextSibling – Helps you find the next sibling of a selected element.
firstSibling – Helps you find the first child of a selected element.
setAttribute() – Sets an attribute of an element.
removeAttribute() – Removes an attribute from an element.
‘click’ – When a mouse button is pressed and released on a single element.
‘keydown’ – When the user pressed a key on their keyboard.
‘keyup’ – When the user releases a key on the keyboard.
‘focus’ – When an element is Focused.
‘blur’ – When an element loses focus.
‘submit’ – When the user submits a form.
‘load’ – When the page finishes the loading.
‘resize’ – When the browser resizes.
‘scroll’ – When the page is being scrolled up or down.
‘ondrag’ – When the element is being dragged.
‘ondragend’ – When the user has finished dragging a particular element.
‘ondrop’ – When dragged element is dropped on its target.
‘oncopy’ – When the user copies the content of an element.
‘oncut’ – When the user cuts the content of an element.
‘onpaste’ – When the user pastes a content in an element.
Download your free Ebook
Download a free copy of our newest E-book on "Metadata HTML Elements".
Awesome!
Download a free copy of our newest E-book on "Metadata HTML Elements".