What is variable typing?

Forums JavaScriptWhat is variable typing?
Staff asked 7 months ago

Answers (1)

Add Answer
Staff answered 7 months ago

Variable Typing:

Like PHP, JavaScript is a very loosely typed language; the type of a variable is determined only when a value is assigned and can change as the variable appears in different contexts. Usually, you don’t have to worry about the type; JavaScript figures out what you want and just does it.

Example:

  1. The variable n is assigned the string value '838102050', the next line prints out its value, and the typeof operator is used to look up the type.
  2. n is given the value returned when the numbers 12345 and 67890 are multiplied together. This value is also 838102050, but it is a number, not a string. The type of the variable is then looked up and displayed.
  3. Some text is appended to the number n and the result is displayed.

Code:

<script>
n = '838102050'        // Set 'n' to a string
document.write('n = ' + n + ', and is a ' + typeof n + '<br />')

n = 12345 * 67890;     // Set 'n' to a number
document.write('n = ' + n + ', and is a ' + typeof n + '<br />')

n += ' plus some text' // Change 'n' from a number to a string
document.write('n = ' + n + ', and is a ' + typeof n + '<br />')
</script>

Output:

n = 838102050, and is a string
n = 838102050, and is a number
n = 838102050 plus some text, and is a string

 

Subscribe

Select Categories