The Basics JavaScript

Ace your homework & exams now with Quizwiz!

What is the answer? let x = 16 + 4 + "Volvo"

20Volvo

What method do I use to find the length of the string? let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

let length = text.length;

The solution to avoid this problem is to use the backslash escape character. The backslash (\) escape character turns special characters into string characters: let text = "We are the so-called ________________ from the north.";

let text = "We are the so-called \"Vikings\" from the north.";

The trim() method removes whitespace from both sides of a string. You may want to do this for security reasons. We will discuss later. let text = " Hello World! "; remove the white space.

let text.trim() // Returns "Hello World!"

A string is converted to upper case with toUpperCase(): convert text1 to upper case by assigning it to text2. let text1 = "Hello World!";

let text2 = text1.toUpperCase();

concat() joins two or more strings: join text1 with text2 assigning the result to text3. let text1 = "Hello"; let text2 = "World";

let text3 = text1.concat(" ", text2);

Use the length property to alert the length of txt. let txt = "Hello World!"; let x = _______________ ; alert(x);

let txt = "Hello World!"; let x = txt.length ; alert(x);

Use escape characters to alert We are "Vikings". let txt = "_________________"; alert(txt);

let txt = "We are \"Vikings\"; alert(txt);

Statement: Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

let x = toCelsius(77); let text = "The temperature is " + x + " Celsius";

Extra large or extra small numbers can be written with scientific (exponential) notation: Give two examples of this.

let y = 123e5; // 12300000 let z = 123e-5; // 0.00123

JavaScript variables are containers for data values. Objects are variables too. But objects can contain __________ values. Objects use property/key:________ pairs.

many value const car = {type:"Fiat", model:"500", color:"white"}; const car = {key:value, key:value, key:value}

How do you invoke myFunction? function myFunction() { console.log ( "call me") }

myFunction( ) ( ) the use of "( )" invokes the function.

Execute the following function: function myFunction() { alert("Hello World!"); }

myFunction()

What is returned? typeof 0 + "<br>" + typeof 314 + "<br>" + typeof 3.14 + "<br>" + typeof (3) + "<br>" + typeof (3 + 4);

number for each

In real life, a car is an ____________. A car has ___________ like weight and color, and _________ like start and stop:

object properties methods

You access an object method with the following syntax:

objectName.methodName()

You can access object properties in two ways. What are the two ways?

objectName.propertyName objectName["propertyName"]

Complete: <button = ______________="alert('Hello')">Click me.</button>

onclick

The "this" key word: In a function definition, this refers to the "________" of the function. In the example above, this is the person object that "__________" the fullName function

owner owns In other words, this.firstName means the firstName property of this object.

Function _____________ are listed inside the parentheses () in the function definition. Function ___________ are the ________ received by the function when it is invoked. Inside the function, the arguments (the parameters) behave as ________________.

parameters arguments are the values local variables.

What are primitive values?

Primitive In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null. Most of the time, a primitive value is represented directly at the lowest level of the language implementation.

You can also break up a code line within a text string with a single backslash: document.getElementById("demo").innerHTML = "Hello \Dolly!";

The \ method is not the preferred method. It might not have universal support.Some browsers do not allow spaces behind the \ character.

Can you can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Yes, let answer1 = "It's alright"; // Single quote inside double quotes. let answer2 = "He is called 'Johnny' "; // Single quotes inside double quotes let answer3 = 'He is called "Johnny" '; // Double quotes inside single quotes

let carName1 = "Volvo XC60"; // Using double quoteslet carName2 = 'Volvo XC60'; // Using single quotes Are the two equivalent ?

Yes, Strings are written with quotes. You can use single or double quotes: Example

Why Functions? What is the benefit of using functions?

You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.

The typeof Operator can be used for what?

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

It is a common practice to declare objects with the const keyword. const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue", fullName : function() { return this.firstName + " " + this.lastName; } }; What do you type to execute the function fullName()?

person.fullName() will execute the function.

JavaScript objects are containers for named values called properties. How can you access "lastName" in the object person? const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"};

person.lastName; person["lastName"];

We have an object. A car Properties are: car.name = Fiat car.model = 500 car.weight = 850kg car.color = white What are the property-value pairs for this object?

property = name, value=Fiat property = model, value=500 property = weight, value=850kg property = color, value=white

Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties. Name some string methods for let txt = "abcd" :

txt.length txt. slice(start, end) txt. substring(start,end) substr(start,end)

Objects are ________________ too. But objects can contain many values.

variables

What are the obscure Arithmetic Operators in JavaScript

%Modulus (Division Remainder) ++Increment --Decrement

What is the shortcut operator to 10 - 2? What is the shortcut operator to 10/5? What assignment operator assigns a remainder to a variable?

10 -+ 2 // 8 10 /+ 5 // 2 10 %= 4 // 2

Normally, JavaScript strings are primitive values, created from literals: What is a string literal?

A literal is a value written exactly as it's meant to be interpreted. A string literal is zero or more characters, either enclosed in single quotation (') marks or double quotation (") marks. You can also use + operator to join strings.

The concat() method can be used instead of the plus operator. These two lines do the same: text = "Hello" + " " + "World!"; text = "Hello".concat(" ", "World!");

All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced.

An HTML event can be something the browser does, or something a user does. What are some events that happen in HTML?

An HTML web page has finished loading An HTML input field was changed An HTML button was clicked

Name the operators in JavaScript.

Arithmetic Operators +, -, *, /, %, --, ++ Comparison Operators ==, !=, <, >, <= ect. Logical (or Relational) Operators && , ||, ! Assignment Operators =, +=, -=, *=, /=, Conditional (or ternary) Operators

substring() is similar to slice(). The difference is that substring() cannot accept negative indexes. let str = "Apple, Banana, Kiwi"; let part = substring(7, 13); What is the result?

Banana If you omit the second parameter, substring() will slice out the rest of the string resulting in the same as slice(). Banana, Kiwi

What will the result be? let str = "Apple, Banana, Kiwi"; let part = str.slice(7, 13);

Banana Why? We start slicing at the 7th character, and end at the 13th character. Space included. " " is one character. Start at the "B" [7] and on the 13th character, the "',". leaving Banana. Remember: JavaScript counts positions from zero. First position is 0.

If you omit the second parameter, the method will slice out the rest of the string: let str = "Apple, Banana, Kiwi"; let part = str.slice(7); What is the result?

Banana, Kiwi

What is a Boolean? What can the values be?

Booleans can only have two values: true or false. let x = 5; let y = 5; let z = 6; (x == y) // Returns true (x == z) // Returns false

What are variables? What are 3 ways to declare a JavaScript variable?

Containers for stroing data (values) var let const

Objects can NOT contain functions? True/False?

False const person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; Annonymous function here. Not hoisted.

You can declare Strings, Numbers, and Booleans as Objects! True/False?

False: When a JavaScript variable is declared with the keyword "new", the variable is created as an object: Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.

What are events in JavaScript?

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events.

JavaScript code is often several lines long. It is more common to see event attributes calling functions: <button onclick="displayDate()">The time is?</button>

Here is a list of events: onchange - html element has changed. onclick - html element was clicked onmouseover - mouse moved over html element onmouseout - moved mouse out of html element. onkeydown - pressed key down onload - html was loaded. This is only a few events in JS. There are many.

Explain the "this" key word in our person object. const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue", fullName : function() { return this.firstName + " " + this.lastName; } };

In a function definition, this refers to the "owner" of the function. In the example above, this is the person object that "owns" the fullName function. In other words, this.firstName means the firstName property of this object.

Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With single quotes: <element event='some JavaScript'>

In the following example, an onclick attribute (with code), is added to a <button> element: <!DOCTYPE html> <html> <body> <button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button> <p id="demo"></p> </body> </html>

If the first parameter is negative, the position counts from the end of the string. let str = "Apple, Banana, Kiwi"; let part = str.substr(-4);

Kiwi

Variables declared within a JavaScript function, become _________ to the function. Local variables can only be accessed from _____________ the function.

Local within

JavaScript arrays are written using ("Saab", "Volvo", "BMW") Array items are separated by commas ? The following code declares (creates) an array called cars, containing three items (car names):

No, we use square brackets const cars = ["Saab", "Volvo", "BMW"]; Yes, we use comas to separate the items in an array. Array indexes are zero-based, which means the first item is [0], the second is [1], and so on.

What are some data types in JavaScript?

Number 2, 2.35 String "life" , 'love'

What are some Datatypes in JavaScript?

Numbers: 1, 2, 3, 125.6 Strings : "I am a string" Boolean: true or false Null : The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations. Undefined: A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.

To replace case insensitive, use a regular expression with an /i flag (insensitive): text.replace( /MICROSOFT/i ,"InnovativeTechnocrates");

Please visit InnovativeTechnocrates!

The replace() method replaces a specified value with another value in a string: The replace() method does not change the string it is called on. It returns a new string. let text = "Please visit Microsoft!"; let newText = text.replace("Microsoft", "InnovativeTechnocrates");

Please visit InnovativeTechnocrates! By default, the replace() method replaces only the first match: By default, the replace() method is case-sensitive. Writing MICROSOFT (with upper-case) will not work:

A JavaScript function is a block of code designed to perform a particular ______________________ (fill in the blank). A JavaScript function is executed when it is _____________________.

Task; Invoked or Called

JavaScript objects are written with curly braces {}. Object properties are written as name: value pairs, separated by commas.

Yes we use curly braces for objects: const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

Explain the variable "let"

The let keyword was introduced in ES6 (2015). Variables defined with let cannot be Redeclared. Variables defined with let must be Declared before use. Variables defined with let have Block Scope.

What is the difference between an Operator & Operands?

The numbers (in an arithmetic operation) are called operands. The operation (to be performed between the two operands) is defined by an operator. Operand 100 Operator + Operand 50

If a parameter is negative, the position is counted from the end of the string. This example slices out a portion of a string from position -12 to position -6: let str = "Apple, Banana, Kiwi"; let part = str.slice(-12, -6);

The slice() method extract a part of a string and returns the extracted parts in a new string: Banana

Because strings must be written within quotes, JavaScript will misunderstand this string: let text = "We are the so-called "Vikings" from the north."; What will this string result in if we console.log(text)?

The string will be chopped to "We are the so-called ". Why?

ECMAScript 2017 added two String methods: padStart and padEnd to support padding at the beginning and at the end of a string. The padStart() method pads a string with another string:

There are 3 methods for extracting string characters: charAt(position) charCodeAt(position) Property access [ ]

Methods are functions used within an object class. True/False?

Ture

You define (and create) a JavaScript object with an object literal: Object literal is an object that has zero or more characters enclosed in double (") or single quotation marks (') Create an object which we will call person that contains the following key value pairs.

const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"};

For best readability, programmers often like to avoid code lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

document.getElementById("demo").innerHTML = "Hello Dolly!";

A safer way to break up a string, is to use string addition: or adding to strings together: "add" + "me" document.getElementById("demo").innerHTML = "Hello " _______ "Dolly!";

document.getElementById("demo").innerHTML = "Hello " +"Dolly!";

If you access a method without the () parentheses, it will return the _______________________.

function definition: const person = { firstName: "John", lastName : "Doe", id : 5566, fullName : function() { return this.firstName + " " + this.lastName; } }; // function() { return this.firstName + " " + this.lastName; }

Statement: A JavaScript function (function declaration) is defined with the function keyword, followed by a name, followed by parentheses (). Function declarations are hoisted. A JavaScrupt function that does not have a name is an anonymous function or a function expression. They are not hoisted. 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 name(parameter1, parameter2, parameter3) { // code to be executed }

what does slice() do?

slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the start position, and the end position (end not included).

When JavaScript reaches a return statement, the function will stop E_________. Functions often compute a return "v______________".. The return value is " r__________" back to the "caller":

stop executing return value returned

Normally, JavaScript strings are primitive values, created from literals: let x = "John"; But strings can also be defined as objects with the keyword new: let y = new String("John");

string object Take a look a the attached code.

The typeof operator returns the type of a variable or an expression: What does typeof return in this instance? typeof "" + "<br>" + typeof "John" + "<br>" + typeof "John Doe";

string for each.

A string is converted to upper case with toUpperCase(): convert text1 to lower case by assigning it to text2. let text1 = "Hello World!";

text2 = text1.toLowerCase();


Related study sets

Managerial Ethics Midterm 2020- Quiz Questions

View Set

5.Sınıf 1.Ünite Hello 26.Ders Ders Programı Sorma

View Set

SUCCESS! In Clinical Laboratory Science - Blood Bank: Blood Groups, Genetics, Serology

View Set

Chapter 5: Florida Statutes, Rules and Regulations Common to All Lines

View Set

accounting ch.1-3 vocab&some online work

View Set

Famous Photographers & Photography Careers

View Set

Evolve Adaptive Quiz - Delegation

View Set