JavaScript Basics and Features

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

JavaScript is primarily used for:

  • Creating operating systems.
  • Client-side scripting to enhance web page interactivity. (correct)
  • Server-side scripting to manage databases.
  • Developing mobile applications exclusively.

Brendan Eich created JavaScript at Netscape in what year?

  • 1990
  • 2005
  • 1995 (correct)
  • 2000

What does ECMAScript refer to in the context of JavaScript?

  • A deprecated version of JavaScript.
  • The standardized version of JavaScript. (correct)
  • A JavaScript library for DOM manipulation.
  • A type of comment used in JavaScript code.

When including JavaScript in an HTML document, what is considered the best practice for script placement?

<p>At the end of the <code>&lt;body&gt;</code> section to ensure the page loads first. (B)</p> Signup and view all the answers

Which of the following is a benefit of using external JavaScript files?

<p>They promote reusability across multiple web pages. (C)</p> Signup and view all the answers

What is the purpose of console.log() in JavaScript?

<p>To display output in the browser's JavaScript console for debugging. (D)</p> Signup and view all the answers

Which of the following components can a JavaScript statement contain?

<p>Keywords, operators, and values. (B)</p> Signup and view all the answers

How does JavaScript handle whitespace?

<p>It ignores extra spaces, tabs, and line breaks. (B)</p> Signup and view all the answers

What is the primary difference between an expression and a statement in JavaScript?

<p>Expressions produce a value, while statements perform an action. (B)</p> Signup and view all the answers

Which of the following is an example of a string literal in JavaScript?

<p>'JavaScript Fun' (A)</p> Signup and view all the answers

Which keyword is used to declare a variable in JavaScript that can be reassigned a new value?

<p>let (D)</p> Signup and view all the answers

What is the purpose of comments in JavaScript?

<p>To explain code for better readability and debugging. (B)</p> Signup and view all the answers

What is a key characteristic of JavaScript variables?

<p>They are loosely typed, allowing them to store any data type without prior declaration. (A)</p> Signup and view all the answers

Which keyword is used to declare a variable whose value cannot be changed after it's assigned?

<p>const (B)</p> Signup and view all the answers

What is the purpose of the typeof operator in JavaScript?

<p>To reveal the current variable type. (D)</p> Signup and view all the answers

What happens when JavaScript reaches a return statement in a function?

<p>The function stops executing and returns a value to the caller. (B)</p> Signup and view all the answers

What is function hoisting in JavaScript?

<p>The mechanism where function declarations are conceptually moved to the top of their scope before code execution. (D)</p> Signup and view all the answers

What is lexical scope in JavaScript?

<p>The environment in which the variable was created and can be global, local, or closure. (D)</p> Signup and view all the answers

What will '42' + 8 result in, and why?

<p>428, because JavaScript performs string concatenation. (D)</p> Signup and view all the answers

What does the isNaN() function do in JavaScript?

<p>Checks if a value is not a number. (A)</p> Signup and view all the answers

JavaScript code can only be included directly within an HTML document.

<p>False (B)</p> Signup and view all the answers

In JavaScript, the innerText property is used to insert text into an HTML element with a specified ID.

<p>True (A)</p> Signup and view all the answers

The console.xml() method is the primary method for displaying output in the browser's JavaScript console.

<p>False (B)</p> Signup and view all the answers

In JavaScript, extra whitespace, tabs, and line breaks are significant and will cause errors.

<p>False (B)</p> Signup and view all the answers

In JavaScript, every statement must end with a semicolon (;).

<p>False (B)</p> Signup and view all the answers

In JavaScript, keywords are special characters that perform operations on operands.

<p>False (B)</p> Signup and view all the answers

In JavaScript, a function must always return a value.

<p>False (B)</p> Signup and view all the answers

In JavaScript, variables declared with const can be re-assigned new values after their initial assignment.

<p>False (B)</p> Signup and view all the answers

In JavaScript, a variable's data type is declared explicitly when the variable is created.

<p>False (B)</p> Signup and view all the answers

In JavaScript, variables declared inside a function have global scope by default.

<p>False (B)</p> Signup and view all the answers

In JavaScript, variables declared without any keyword, such as var, let, or const, are not automatically declared.

<p>False (B)</p> Signup and view all the answers

JavaScript functions that are defined can be called or ‘invoked’ before their declaration in the code. This feature is called hoisting.

<p>True (A)</p> Signup and view all the answers

A JavaScript function is executed automatically when it is defined.

<p>False (B)</p> Signup and view all the answers

In JavaScript, using single-line comments (//) is appropriate for providing detailed explanations or disabling large blocks of code.

<p>False (B)</p> Signup and view all the answers

In JavaScript, the typeof operator can be used to determine the data type of a variable.

<p>True (A)</p> Signup and view all the answers

In JavaScript, the keywords var, let, and const all have the same behavior regarding scope and reassignment.

<p>False (B)</p> Signup and view all the answers

The primary purpose of the parseInt() function in JavaScript is to convert any value to a floating-point number.

<p>False (B)</p> Signup and view all the answers

The JavaScript expression '50' + 10 will result in the number 60.

<p>False (B)</p> Signup and view all the answers

In JavaScript, the equality operator == only compares the values of two operands, while the strict equality operator === compares both value and type.

<p>True (A)</p> Signup and view all the answers

In JavaScript, the ternary operator is a shorthand way to write single-line comments.

<p>False (B)</p> Signup and view all the answers

Flashcards

What is Javascript?

A scripting language embedded in web browsers that enables client-side scripting, improving web page responsiveness.

What is ECMAScript?

Standardized version of JavaScript by Ecma International.

Javascript: Language basics

Syntax, keywords, operators, and built-in objects of JavaScript.

Web page interaction

Manipulating the DOM for dynamic content in JavaScript.

Signup and view all the flashcards

Web applications

Creating responsive web apps and handling JSON data.

Signup and view all the flashcards

External Javascript File in HTML

Use the <script> tag with the src attribute.

Signup and view all the flashcards

Javascript: Keywords.

Words that have special significance in the JavaScript language.

Signup and view all the flashcards

Javascript: Operators

Special characters that perform an operation on one or more operands.

Signup and view all the flashcards

Javascript: Expressions

Units of code that produce a single value.

Signup and view all the flashcards

Javascript: Expression

Javascript statement that produces a value.

Signup and view all the flashcards

Javascript: Statement

Javascript statement that performs an action.

Signup and view all the flashcards

Number literals

Integer numbers (100) or floating-point numbers (3.142).

Signup and view all the flashcards

Variable Values

Variable values are called, quite simply, “variables" and are used to store data within a script.

Signup and view all the flashcards

Loosely typed variable

Can store any data type without prior declaration.

Signup and view all the flashcards

Strongly-typed variable

Must declare a specific data type before use.

Signup and view all the flashcards

Javascript Variables using 'var'

The var keyword should only be used in code written for older browsers.

Signup and view all the flashcards

Javascript variables using 'let'

Variables declared with let can be reassigned new values as the script proceeds.

Signup and view all the flashcards

Javascript variables using 'const'

Constant values and cannot be changed.

Signup and view all the flashcards

Parsing failure

Returns NaN (Not a Number).

Signup and view all the flashcards

What is scope?

Scope determines where a variable is accessible in a script.

Signup and view all the flashcards

Console Output for Debugging

Displaying content to the browser's console for debugging purposes.

Signup and view all the flashcards

Inline JavaScript

Inserting JavaScript code directly within HTML using <script> tags.

Signup and view all the flashcards

What is Syntax?

The rules that govern the Javascript scripting language.

Signup and view all the flashcards

Whitespace in JavaScript

Extra spaces, tabs, and line breaks, ignored by Javascript.

Signup and view all the flashcards

What is a variable?

A container in which data can be stored and retrieved later.

Signup and view all the flashcards

Automatically defined Javascript variables

Automatically declared when first used.

Signup and view all the flashcards

What is a Javascript function?

A block of code designed to perform a particular task, which returns a final single value.

Signup and view all the flashcards

Function Arguments

Values received by a function when it is invoked.

Signup and view all the flashcards

Anonymous Javascript functions

A function that is assigned to a variable.

Signup and view all the flashcards

Function Hoisting

Occurs when JavaScript reads scripts, function declarations are can be called before they are defined.

Signup and view all the flashcards

Global Scope

A type of scope declared outside of any function.

Signup and view all the flashcards

Local Scope

A type of scope declared inside a function.

Signup and view all the flashcards

parseInt()

Converts a string value to an integer.

Signup and view all the flashcards

parseFloat()

Converts a string value to a floating-point number.

Signup and view all the flashcards

String()

Converts a number to a string data type.

Signup and view all the flashcards

toString()

A number to string method that converts a number to a string data type.

Signup and view all the flashcards

Modulus (%)

Arithmetic operator that returns the remainder of a division.

Signup and view all the flashcards

Shorthand Assignment Operators

A shorthand assignment operator performs an operation and assign the result in a single step.

Signup and view all the flashcards

Ternary operator(?:)

Also known as a conditional operator can evaluate if statement is true or false.

Signup and view all the flashcards

Javascript: Equality (===)

Returns true if both value and type are identical.

Signup and view all the flashcards

Study Notes

Basics of JavaScript

  • JavaScript is an object-based scripting language embedded in web browsers like Chrome, Edge, and Firefox.
  • It enables client-side scripting, which enhances web page responsiveness.
  • Brendan Eich created it at Netscape in 1995 as LiveScript.
  • It was renamed JavaScript to capitalize on Java's popularity, but it isn't related.
  • JavaScript leads to faster, more interactive, and dynamic web experiences directly in the browser.

JavaScript Evolution & Key Features

  • Microsoft's introduction of JScript caused fragmentation concerns.
  • In 1997, JavaScript was standardized as ECMAScript by Ecma International.
  • Despite standardization, it's still known as JavaScript.
  • Brendan Eich co-founded Mozilla and launched Firefox.
  • Language basics include syntax, keywords, operators, and built-in objects.
  • Web page interaction involves manipulating the DOM for dynamic content.
  • Web applications include creating responsive web apps and handling JSON data.

Including Scripts

  • JavaScript code can be directly embedded in an HTML document between <script> tags.
  • To include JavaScript code directly in an HTML document it must be inserted between <script> tags.

document.getElementById( 'message' ).innerText = 'Hello World!'

  • JavaScript can be placed in the <head>, <body>, or end of the <body> sections within an HTML document.
  • Placing JavaScript in the <head> is not usually recommended, unless it's a small script.
  • Placing JavaScript inside the <body> can cause page rendering delays.
  • Placing JavaScript at the end of the <body> section is the best practice, as it ensures the page loads before scripts run.
  • JavaScript code can be written in external .js files.
  • External JavaScript files are included using the <script> tag with the src attribute.
<script src="external_script.js"></script>
  • External JavaScript files promote reusability across multiple web pages.
  • External JavaScript files improve organization by separating HTML content from behavior.
  • External JavaScript files allow easier maintenance since updates update all linked pages.
  • The .js files should only contain JavaScript code without <script> tags.

Console Output

  • JavaScript can dynamically write content into an HTML element using the innerText property to insert text into the element with the specified ID.
  • Example: document.getElementById('message').innerText = 'Hello World!';
  • JavaScript can display output using a pop-up alert.
  • Use window.alert('Hello World!'); to display 'Hello World!' in a dialog box.
  • The console.log() method of the console object can display content in the browser's JavaScript console for debugging.
  • When learning JavaScript, it is better to display output in the browser's console using console.log('Hello World!');

Making Statements

  • JavaScript code comprises instructions called “statements,” generally executed top-to-bottom by the browser’s JavaScript engine.
  • Statements can contain keywords, operators, values, and expressions.
  • Keywords are words with special significance in the JavaScript language.
  • Operators are special characters that perform operations on operands.
  • Values include text strings, numbers, boolean true or false, and null.
  • Expressions are units of code that produce a single value.

JavaScript Statement Termination & Readability

  • In earlier JavaScript, every statement needed to end with a semicolon (;).
  • Semicolons are now optional unless multiple statements are on the same line.
  • Some developers prefer using semicolons for clarity.
  • Whitespace (extra spaces, tabs, and line breaks) is ignored in JavaScript.
  • Spacing can improve readability in JavaScript.
  • Use the space bar for indenting statements, as tab spacing may be treated differently in editors.
  • Example of Readable Code: total = 100 + 200;
  • Examples of Less Readable Code: total=100+200;
  • Expressions produce a value and are used in calculations or function returns, example expression: (80 + 20) → 100
  • Statements perform an action, like declaring variables or running loops, example statement: let total = 300;

JavaScript Statements & Syntax

  • The rules governing the JavaScript language are “syntax.”
  • JavaScript statements are often grouped using curly brackets {} inside function blocks.
  • These blocks allow reusable execution when required.
  • Indent statements by two spaces inside curly brackets for readability.
{
  statement
  statement
}

JavaScript Values

  • JavaScript recognizes two types of values: fixed values and variable values.
  • Fixed values (literals) can be number literals or string literals
  • Number literals can be integer numbers, example 100, or floating-point numbers, example 3.142.
  • String literals are text enclosed in single 'JavaScript Fun' or double "JavaScript Fun" quotes.
  • Be consistent with string literals, i.e. only use single or double quotes.

JavaScript Variable Values

  • Variable values are called "variables" used to store data within a script.
  • Variables are created using a JavaScript keyword, for instance, let total.
  • The JavaScript assignment operator (=) is used to assign a value to the variable, for instance let total = 300.
  • An expression produces a single value with values and operators.
  • Example Numeric Expression: let result = (80 + 20);
  • Example Expression With Variables:
let total = 300;
let newTotal = (total - 200);
  • Example Operators Used In Expressions: let finalValue = (100 + 50) * 2; // 300
  • JavaScript is case-sensitive, so total and Total are different variables.
  • Comments can explain code for better readability and debugging
  • Use single-line comments // for short explanations
  • Use multi-line comments /*...*/ for longer explanations or disabling blocks of code.
  • Always use comments to explain complex logic.
  • Use comments to “comment-out” lines of code to prevent execution when debugging code.
  • A variable is a container which data can be stored and retrieved later.
  • JavaScript variables are easier to use because they are loosely-typed.

Loosely Typed vs Strongly Typed Variables

  • Strongly typed variables must declare specifics before being used, such as: int age = 25; // Can ONLY store integers
  • Example languages that use strongly typed variables: Java, C++, C#
  • Loosely typed variables can store any data type without prior declaration, such as: let data = 25; // Can Store any type of data
  • Example language that uses loosely typed variables: JavaScript

Declaring Variables

  • Variables can be declared automatically
    • In this first example, x, y, and z are undeclared variables.
    • They are automatically declared when first used.
    • It is considered good programming practice to always declare variables before use.
     x = 5;
     y = 6;
     z = x + y;
  • Variables can be declared using var x = 5
    • The var keyword was used in all JavaScript code from 1995 to 2015.
    • The var keyword should only be used in code written for older browsers.
    var x = 5;
    var y = 6;
    var z = x + y;
  • Variables can be declared using let x = 5 - The let and const keywords were added to JavaScript in 2015. - Variables declared with let can be reassigned new values as the script proceeds - A let variable can be declared without a value and assigned later.
        let myNumber
        myNumber = 5
        let z = x + y;
    - Multiple variables may be declared on a single line too:
    `let i,j,k; or let i = 10, j = 20`
  • Variables can be declared using const x = 5; - const are constant values and cannot be changed. - Use const if the type should not be changed (Arrays and Objects) - Examples usingconst
        const x = 5;
        const y = 6;
        const z = x + y;
  • Use meaningful names for variables to make the script easier to understand later
  • JavaScript sets the variable type for the value assigned automatically.
  • Subsequent assignation of a different data type later in the script can be made to change the variable type.
  • The typeof keyword reveals the current variable type.
  • A JavaScript function is a reusable block of code designed to perform a task and return a single value.
  • Executing a JavaScript function happens when it's called.

JavaScript Function Syntax

  • A function is defined with the function keyword.
  • Include the function’s name.
  • Include parentheses ().
  • Function names can contain letters, digits, underscores, and dollar signs.
  • Parameters (optional) inside the parentheses are separated by commas: (parameter1, parameter2,...).
  • The function’s code goes inside curly brackets {}.
  • Function arguments are values received when the function is called.
  • Inside the function, arguments act as local variables.
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}

Function Invocation & Return

  • Function invocation happens:

    • When an event occurs (e.g., a user clicks a button).
    • When it is invoked (called) from JavaScript code.
    • Automatically (self invoked).
  • When JavaScript reaches a return statement, the function stops executing.

  • If invoked from a statement, JavaScript will return to execute the code after the invoking statement.

  • Functions often compute a return value, returned to the "caller".

let x = myFunction(4, 3);
function myFunction(a, b) {
    // Function returns the product of a and b
    return a * b;
}

Assigning Functions

  • Assigning a named function to a variable e.g.
function add(num1, num2) {
    return num1 + num2
}
let addition = add
console.log(“Result:“, addition(100,200))
  • With anonymous Function Expressions:
let anon = function(num1, num2) {
     return num1 + num2
}

Self-Invoking Functions

  • Self-invoking functions executes example code when the script gets loaded.
(function add(num1, num2) {
    return num1 + num2
})()

Function Hoisting

  • JavaScript reads scripts in two sweeps:
    • First Sweep: Finds function declarations and hoists them to the top.
    • Second Sweep: Executes the script.
  • Function declarations can be called before the function is defined eg:
console.log("Volvo“, add(100,200))
function add(num1, num2) {
    return num1 + num2
}
  • But Function Expressions are NOT Hoisted, the the below example will not work
console.log("Volvo“, add(100,200))
let x = function add(num1, num2) {
        return num1 + num2
    }

Recognizing Scope

  • Scope is where a variable is accessible in a script.
  • JavaScript uses lexical scope, meaning the variable’s environment decides its accessibility.

Types of Scope

  • Global Scope variables are declared outside of any function
  • Global Scope variables are accessible throughout the entire script.
  • Potential Issue: Naming conflicts with external scripts.
let myName = ‘Ahmed';
function readName(a, b) {
    console.log(myName)
}
  • Local Scope variables are declared inside a function.
  • Local Scope variables only exist inside that function and cannot be accessed outside that function
function readName(a, b) {
    let myName = ‘Ahmed';
    console.log(myName)
}

Converting Values

  • JavaScript handles different data types differently.
  • Mixed data types (strings and numbers) can lead to unexpected results
  • Converting a string or other types to numbers is needed to perform proper mathematical operations.
  • Example of Unexpected Behavior: '42' + 8 results in '428' (string concatenation, not addition).
  • The value '42' is a string, but 8 is a number.

Strings to Numbers

  • Strings can be converted to numbers using built-in functions like parseInt() and parseFloat().
  • These functions allow you to work with string values as numeric types in mathematical operations.

Conversion Functions

  • parseInt(): Converts a string to an integer (whole number).
  • Example: parseInt('42') → 42
  • Ignores non-numeric characters after the number.
  • Example: parseInt('42nd Street') → 42
  • parseFloat() Converts a string to a floating-point number.
    • Example: parseFloat('42.5px') → 42.5
    • parseFloat('42.5abc') → 42.5 (alphabetic characters are ignored).

Handling Non-Numeric Values

  • If the conversion fails, JavaScript returns NaN (Not a Number).
  • Example parseInt('Hello') → NaN
  • To check if a value is not a number: isNaN(value) returns true if the value is not a number.
let num = 42;
num.toString(); // Returns '42’

Operators

  • Addition of numbers
  • Concatenation of strings
  • Subtraction
  • Multiplication
  • Division
  • Modulus
  • Increment
  • Decrement
  • Exponentiation

Assignment Operators

=	a = b	a = b
+=	a += b	a = (a + b)
- =	a -= b	a = (a - b)
- =	a *= b	a = (a * b)
/=	a /= b	a = (a / b)
%=	a %= b	a = (a % b)
- *=	a **= b	a = (a ** b)

Comparison Operators

  • Comparison operators are used to evaluate conditions by comparing two values.
  • The === and !== operators ensure strict equality by checking both value and data type, while relational operators like >, <, >=, and <= compare numerical values.
  • Returns true if the first operand is greater.

  • < Returns true if the first operand is smaller.
  • = Returns true if the first operand is greater or equal.

  • <= Returns true if the first operand is smaller or equal.
  • Used frequently in loops and conditional statements.

Ternary Operator

  • The ternary operator (?:) is a shorthand way to evaluate a condition that involves three parts: condition ? expression_if_true : expression_if_false

Summary

  • JavaScript code can be included in an HTML document directly with or from an external file using <script> </script> tags.
  • JavaScript can display output in an HTML element in an alert dialog box or in the browser’s console window.
  • JavaScript statements may contain keywords, operators, values, and expressions.
  • The JavaScript interpreter ignores tabs and spaces.
  • JavaScript statements can be grouped in {} curly bracket function blocks that can be called to execute when required.
  • Variable and function names may comprise letters, numbers, and underscore characters, but must avoid keywords.
  • JavaScript variables may contain data types of String, Number, Boolean, Object, Function, Symbol, null, and undefined.
  • Variables declared with the let keyword can be reassigned new values, the const keyword does not allow this change.
  • A function expression has statements grouped in {} curly brackets for execution, and it returns a final single value.
  • The () parentheses of a function expression may contain parameters for argument values to be passed from the caller.
  • A function block can include a return statement to specify data to be passed back to the caller.
  • The JavaScript () parentheses operator calls the function.
  • Hoisting allows function calls to appear in the script before the function declaration.
  • Anonymous function expressions have no function name.
  • Lexical scope is the environment in which the variable was created and can be global, local, or closure.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

CSD 3313 ES6+ ES6 Quiz
12 questions
JavaScript Basics and Features
40 questions
Use Quizgecko on...
Browser
Browser