JavaScript Programming/Variables and Expressions

From Wikiversity
Jump to navigation Jump to search

This lesson introduces JavaScript variables, data types, expressions, and operators.

Objectives and Skills[edit]

Objectives and skills for this lesson include:[1]

  • Apply JavaScript best practices
    • Comments; indentations; naming conventions; noscript; constants; reserved keywords; debugger keyword; setting breakpoints; console.log
  • Declare and use variables of primitive data types
    • Number; Boolean; String; Null; Undefined; typeof operator; type checking functions; use strict; converting between data types; formatting numbers; string operations; single quote vs double quote (nesting); initialization
  • Complete or debug code that uses assignment and arithmetic operators
    • Assignment; increment; decrement; addition; subtraction; division; multiplication; modulus; compound assignment operators

Readings[edit]

  1. Wikibooks: JavaScript/Variables and types
  2. Wikibooks: JavaScript/Numbers
  3. Wikibooks: JavaScript/Strings
  4. Wikibooks: JavaScript/Operators

Multimedia[edit]

  1. YouTube: JavaScript Tutorial for Beginners - 03 - Variables
  2. YouTube: JavaScript Tutorial for Beginners - 04 - Variables Part 2
  3. YouTube: JavaScript Tutorial for Beginners - 08 - Operators
  4. YouTube: Google Chrome JavaScript Debugger
  5. YouTube: Firefox JavaScript Debugger
  6. YouTube: Conditionals Exercise Solutions
  7. YouTube: Console.log - JavaScript Tutorial for Beginners
  8. YouTube: Math.random / Generate random numbers
  9. YouTube: indexOf() and lastIndexOf() String Methods
  10. YouTube: 20 String Methods in 7 Minutes

Examples[edit]

Activities[edit]

Complete the following activities using external JavaScript code. Apply JavaScript best practices, including comments, naming conventions, and constants. In at least one program, prompt the user for input and use console.log() for output. In another program, prompt the user for input and use document.getElementById().innerText or document.getElementById().innerHTML for output. Use the strict directive. Create test data to validate the accuracy of each program. Add comments at the top of the program and include references to any resources used.

Arithmetic[edit]

  1. Create a program that uses variables for hours and rate per hour and then calculate and displays weekly, monthly, and annual gross pay (hours * rate). Base monthly and annual calculations on 12 months per year and 52 weeks per year.[2]
  2. Create a program that uses variables for years, and then calculate and displays an approximate age in months, days, hours, and seconds. For example, a person 1-year-old is 12 months old, 365 days old, etc.
  3. Review MathsIsFun: US Standard Lengths. Create a program that uses variables for a distance in miles, and then calculate and displays the distance in yards, feet, and inches, or calculate and display the distance in kilometers, meters, and centimeters.
  4. Review MathsIsFun: Area of Plane Shapes. Create a program that uses variables for the dimensions of different shapes and then calculate and displays the area of the shapes. Do not include shape choices. That will come later. For now, just include multiple shape calculations in sequence.
  5. Create a program that calculates the area of a room to determine the amount of floor covering required. The room is rectangular with the dimensions measured in feet with decimal fractions. The output needs to be in square yards. There are 3 linear feet to a yard.[3]
  6. Review MathsIsFun: Order of Operations. Create a program that demonstrates the order of operations. Include parentheses, exponents, multiplication, division, addition, and subtraction in your program. Use variables for the calculations and label the output. For example, part of the program might display:
        1 + 2 * 3 = 7
        (1 + 2) * 3 = 9
        ...

Data Types[edit]

  1. Create a program that initializes different variables with integer, floating point, string, null, and undefined values. Demonstrate various operations and converting between data types. For example, user input is always a string, but adding string values of "1" + "1" is typically "11", whereas, adding numeric values of 1 + 1 is 2. Use typeof to label each variable and the resulting output.
  2. Create a program that demonstrates string operations and string formatting. Define string constants or string literals that include apostrophes ('). Define string constants or string literals that include "quotes". Convert between string and numeric data types using Number() and .toFixed() with two decimal places. Concatenate string literals and variables to display output.

Debugging[edit]

  1. Use the debugger statement to create a breakpoint in one of the programs above. Experiment with single-stepping through the code and viewing script and global values. Add one or more variables to the watch window.
  2. Add a breakpoint to the program somewhere after the debugger statement. After the program stops with the debugger, resume script execution and observe the script stopping at the breakpoint.

Lesson Summary[edit]

  • By convention, JavaScript variable names are written in camelCase.[4]
  • JavaScript constant names are written in UPPER_CASE.[5]
  • JavaScript variable and constant names must be unique. These unique names are called identifiers.[6]
  • Reserved words (for example, continue, debugger, break, etc.) can't serve as variable names.[6]
  • Names can begin only with a letter, an underscore or a dollar sign. Names are allowed to contain numbers, but a number can't be the first character.[6]
  • In Java Script names are case sensitive.[6]
  • JavaScript has 7 data types: Number, String, Boolean, Null, Undefined, Function, and Object. Null and Undefined data types can't contain values.[7]
  • There are 6 types of objects in JavaScriptː Object, Date, Array, String, Number and Boolean.[7]
  • JavaScript has only 1 type of number.[8]
  • With some other languages, like Java and C, there is a special “character” type. JavaScript consist's of only one type, string.[9]
  • The typeof operator is used to find the data type of the variable.[7]
  • JavaScript has built-in functions to work with strings and numbers[10]
  • Strings are written using single or double quotation marks. Quotation marks can be used inside the string if they don't match the ones outside of it.[7] Quotation marks used inside can match the outside ones only if they are preceded by the backslash escape character.[11]
  • You can convert between data types in JavaScript.[7]
  • "use strict" is a literal expression that requires / enforces variable declaration. It allows for cleaner code to be written.[12]

Key Terms[edit]

assignment
Assigning a value to a variable or constant with the "=" operator.[source?]
Boolean
Data type which has only two values, True and False.[13]
camel case
Method of joining multiple words into one variable name where the first word is not capitalized and every subsequent word is capitalized.[source?]
console.log
A function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.[source?]
constant
A container for storing a permanent data value that cannot be changed later in the program.[14]
null
A special value which represents "nothing." It is not a reference to a null pointer.[13]
number
Data type in JavaScript which represents both integers and floating-point value.[13]
object
A variable that can contain many values.[15]
string
Can consist of one character or many. A string must be surrounded by quotation marks.[13]
type coercion
The automatic or implicit conversion of values from one data type to another (such as strings to numbers).[16]
undefined
A variable which has not been assigned a value. If a variable is simply declared, but not assigned anything, it becomes undefined.[13]
variable
A container for storing a data values.[6]

See Also[edit]

References[edit]

  1. Microsoft: Exam 98-382 Introduction to Programming Using JavaScript
  2. PythonLearn: Variables, expressions, and statements
  3. Wikibooks: Programming Fundamentals/Practice: Data and Operators
  4. https://google.github.io/styleguide/jsguide.html
  5. https://google.github.io/styleguide/jsguide.html
  6. 6.0 6.1 6.2 6.3 6.4 W3Schoolsː JavaScript Variables
  7. 7.0 7.1 7.2 7.3 7.4 W3Schoolsː JavaScript Data Types
  8. W3Schoolsː JavaScript Numbers
  9. "Data types". javascript.info. Retrieved 2019-09-05.
  10. MDN Web Docs: Data Types and Data Structures
  11. W3Schoolsː JavaScript Strings
  12. W3Schoolsː JavaScript Use Strict
  13. 13.0 13.1 13.2 13.3 13.4 JavaScript.Infoː Data Types
  14. W3Schools: JavaScript const
  15. W3Schoolsː JavaScript Objects
  16. MDNː Type coercion