KE
  • dotNet Web 3.0
  • Engineering Management
    • Process Planning (SDLC)
      • Software development process
      • Basics of SDLC models
      • Scrum
      • Kanban
      • Scrum vs Kanban: applicability
      • Scrumban
    • Estimation
      • Scope Concept
      • Estimates, Targets, and Commitments
      • Overestimate vs Underestimate
      • Decomposition and Recomposition
      • Analogy-based estimations
      • Estimating in Agile
  • Requirements
    • Software Requirements Engineering
      • Requirement definition
      • Levels of Requirements
      • Most common requirements risks
      • Characteristics of Excellent Requirements
      • Benefits from a High-Quality Requirements Process
      • Root Causes of Project Success and Failure
  • Design
    • OOD
      • Abstraction
      • Encapsulation
      • Inheritance vs Aggregation
      • Modularity
      • Polymorphism
      • Abstraction Qualities (cohesion, coupling, etc)
      • Types vs. Classes
      • Separation of concerns principle
      • SOLID
      • Design Patterns
        • Structural patterns
        • Creational patterns
        • Behavioral patterns
      • Most often used design patterns
      • Software Architecture Patterns (structure, pros & cons)
      • Inversion of Control Containers and the Dependency Injection pattern
      • Domain-Driven Design patterns
      • Anti-patterns
    • DB Design
      • Relational Terminology: Entities
      • Relational terminology: Attributes
      • Relational terminology: Records (Tuples)
      • Relationships (One-to-One, One-to-Many)
      • Understanding ER notation
      • Understanding normalization concept
      • Data Integrity
    • Modeling
      • UML: Basic Diagram Types
      • UML: Use Case Diagram (Essentials)
      • UML: Class Diagram (Essentials)
      • Entity Relationship Diagrams
      • Data Flow Diagrams
    • Security
      • Information security concepts
      • Access Control Lists (ACLs)
      • Access Control Models
      • .NET Cryptography Model
      • ASP.NET Identity
      • OWASP Top 10
      • Cross-Site Request Forgery (XSRF)
      • Protecting against cross-site scripting attacks (XSS)
      • Protecting against buffer overrun attacks
      • Protecting against SQL-injection attacks
      • CSRF/XSRF protection
    • Algorithms
      • Algorithms complexity (understanding, big O notation, complexity of common algorithms)
      • Array sorting methods (bubble sort, quick sort, merge sort)
      • Tree structure (construction, traversal)
      • Binary search algorithm
      • Hash table (creating, collisions)
      • Stack, queue, linked list (construction, understanding, usage)
  • Construction Core
    • Programming language
      • Declare namespaces, classes, interfaces, static and instance class members
      • Types casting
      • Value and reference types. Class vs Struct usage.
      • Properties and automatic properties
      • Structured Exception Handling, Exception filters
      • Collections and Generics
      • Dictionaries. Comparison of Dictionaries
      • Building enumerable types
      • Building cloneable objects
      • Building comparable types
      • Nullable types
      • Delegates, events and lambdas
      • Indexers and operator overloading
      • Anonymous types
      • Extension methods. Practices.
      • Custom Type Conversions (implicit/explicit keywords)
      • Strings and StringBuilder. String concatenation practices. String Interpolation
      • Serialization
      • System.IO namespace
      • LINQ to Objects
      • General Coding conventions for C#
      • Static Using Statement
      • Type Reflection
      • Custom attributes
      • Dispose and Finalizable patterns
      • Garbage collection
      • .Net Diagnostics
      • Implementing logging
      • Exception handling guidelines
      • Regular Expressions
      • Span<T> struct
      • C# - What's new?
      • .NET Standard overview
    • Concurrency
      • Understand differences between Concurrency vs Multi-threading vs Asynchronous
      • Concurrency: An Overview
      • Async basics
      • Task Parallelism
      • Basic Synchronization in C#
      • Deadlock problem
      • QueueBackgroundWorkItem or IHostedService for .NET Core
      • How to run Background Tasks in ASP.NET
    • Refactoring
      • Refactoring Concept (what/when/why)
      • Smells Catalog and possible re-factorings
      • Moving Features Between Objects (basic)
      • Organizing Data (basic)
      • Composing Methods (basic)
      • Simplifying Conditional Expressions (basic)
      • Making Method Calls Simpler
      • Dealing with Generalization
    • Product deploying, software installation
      • Create, configure, and publish a web package (.NET Web Profile)
      • Publishing Web Services
      • Manage packages by using NuGet, NPM and Bower
    • Networking
      • Understanding networks: layers and protocols
      • Basic understanding of TCP/IP model and protocols
      • Defining internet, intranet and VPN
      • Basics of Firewalls and DMZ
      • Application layer protocols basics (HTTP, FTP, Telnet)
      • Understanding HTTP and WWW
      • Basic troubleshooting tools (ICMP, ping, traceroute)
      • Client/Server model
      • Sockets, IP and port addressing
      • Using proxy server
      • File transfer services: FTP, TFTP
      • Name resolution services: DNS, whois
      • Remote access services: Telnet, SSH, rdesktop, VNC
      • The basic difference between HTTP and HTTPS protocols
  • Construction Web
    • Web server applications
      • ASP.NET Core
        • Application startup
        • Middleware
        • Working with Static Files
        • Routing
        • Error Handling
        • Globalization and localization
        • Configuration
        • Logging
        • File Providers
        • Dependency Injection
        • Working with Multiple Environments
        • Hosting
        • Managing Application State
        • Request Features
      • ASP.NET Core MVC
        • MVC basics (Model, View, Controller, DI)
        • Model binding and validation
        • View (Razor compilation, Layout, Tag Helpers, Partial Views, DI, View components)
        • Controllers (Route to actions, File uploads)
      • Security and Identity (concepts understanding)
        • Authentication
        • Using identity
        • Authorization with roles
      • Bundle and Minify assets
      • Develop ASP.NET Core MVC apps
      • Advanced topics for ASP.NET Core MVC
        • Application model
        • Filters
        • Areas
        • Application Parts
        • Custom Model Building
        • IActionConstraint
      • Host and deploy ASP.NET Core
      • Migrate from ASP.NET to ASP.NET Core
      • Troubleshoot ASP.NET Core projects
      • Open Web Interface for .NET (OWIN)
      • Web server implementations in ASP.NET Core
    • Web Services
      • REST
      • ASP.NET Web API
        • Routing
        • Configuration
        • Basic error handling
      • Web API-based services
      • Web API Security
      • Token based security
      • SingalR
      • Serialization Frameworks
      • Implement caching
      • gRPC on ASP.NET Core
      • API versioning
      • API documentation
    • Microservices and Cloud
      • Microservices architecture
      • Dockerize a .NET Core application
      • Development workflow for Docker apps
    • JavaScript, HTML, CSS
      • JavaScript: Variables
      • JavaScript: Data types and types conversion
      • JavaScript: Operators
      • JavaScript: Control and Loop constructions
      • JavaScript: Functions, Execution Context and Variables scopes
      • JavaScript: Arrays
      • JavaScript: JS in WebBrowser and basic DOM manipulations
      • HTML: Basic elements
      • CSS: Simple Style rules
      • CSS: selectors
      • Box model
      • HTML: Standards and Browser compatibility
      • HTML: Page Layouts with divs
      • HTML: Frames
      • CSS: Elements positioning and layering
      • CSS: Tables properties
      • CSS: Flexbox
      • Different storage
      • JavaScript: Event Understanding (propagation, capturing, attach/detach)
      • JavaScript: Closure
      • AJAX/JSON
      • Ecma script 6: OOP
      • Promise
      • Strict mode of javascript
    • JavaScript Frameworks
      • Selecting elements
      • Operating on collection
      • Manipulating with elements, working with properties, attributes and data
      • Events
      • animation and effects
      • utilities and Ajax
      • SPA (SINGLE PAGE APPLICATIONS)
      • EcmaScript 6
      • UI frameworks basics:
      • NPM basics:
      • React basics
  • Construction DB
    • SQL
      • Tables, relationships, keys, constraints understanding
      • DDL, DML, DCL understanding
      • SQL data types
      • SQL operators, functions
      • Data manipulation (insert, update, delete)
      • Retrieving data (simple select statement)
      • Joins understanding
      • Creating, modifying, removing database objects
      • Aggregations (ORDER BY, GROUP BY, HAVING, SUM, COUNT, AVG, etc)
      • Combining the results of multiple queries (UNION, EXCEPT, INTERSECT, MINUS, subqueries)
      • Sessions, transactions, locks
      • Isolation levels understanding
      • Implementing stored procedures, user-defined functions, triggers
      • Cursors
    • Data Access Layer
      • Manage connection strings and objects
      • Working with data providers
      • Connect to a data source by using a generic data access interface
      • Handle and diagnose database connection exceptions
      • Manage exceptions when selecting, modifying data
      • Build command objects and query data from data sources
      • Retrieve data source by using the DataReader
      • Manage data by using the DataAdapter and TableAdapter
      • Updating data
      • Entity Framework
        • Query data sources by using EF
        • Code First to existing DB
        • Entity Data Modeling Fundamentals
        • Querying Data
        • Data modification
  • Verification
    • Code Quality
      • MSDN: Guidelines for Names
      • SDO Best Practices Catalog - Coding Standards
      • SDO Best Practices Catalog - Code Review Process
      • SDO Best Practices Catalog - Automatic Code Inspection
      • Automated coding standards enforcement (StyleCop, Resharper)
      • Code Reviews and Toolset
      • Use Work Items (TODO, BUG etc.)
      • Preemptive Error Detection
      • Desirable characteristics of a design (minimal complexity, ease of maintenance, minimal connectednes
      • Creating high quality classes
      • Creating high quality methods
      • Guidelines for initializing variables
      • Exceptions and error handling techniques
      • Best practices of working with data types
      • Code commenting practices
    • Automated Testing (principles, patterns, and practices)
      • Software testing basic concepts
      • Software testing concept
      • Test Case
      • Test Suite
      • Test Plan
      • Testing Levels
      • Naming standards for unit tests
      • Types of test doubles (Stub, Mock, Spy, Fake, Dummy)
      • Basic coverage criteria
      • Testing concepts (Unit vs Functional vs Integration)
      • Goals of Unit Testing, What Makes a Test Valuable?
      • Styles of Unit Testing (Output / State / Collaboration)
      • Good unit test properties
      • F.I.R.S.T Principles of unit testing
      • Test Pyramid concept
      • Testing Pyramid, Agile Testing Pyramid, Diamond
      • Breaking the dependency, Interaction testing
      • Strategies for isolating the database in tests
      • Test smells and how to avoid
      • Test Organization patterns
      • Fixture setup patterns
      • Test double patterns
      • Feature-driven development (FDD)
      • Behavior-driven development (BDD)
      • Test-driven development (TDD)
      • Acceptance testing, Acceptance Test Driven Development (ATDD)
      • Continuous testing
    • Automated Testing (Frameworks, Tools, Libraries)
      • .NET unit test frameworks overview
      • .NET Mocking Frameworks, a comparison
      • xUnit
        • Primary test framework attributes
        • Asserts
        • Exception Handling in Unit Tests
        • Skipping Tests
        • Initialization and Cleanup (Assembly, Class, Test)
        • Data-driven Tests
      • NSubstitute
        • Mocking Method Calls (Using Mock Object, Return Values, Argument Matching)
        • Behavior Verification (Method Was/Not Called, a Specific Number of Times, Getter/Setter Was Called)
        • Throwing exceptions
        • Raising Events from Mock Objects
        • Returning Different Results for Sequential Calls
      • AutoFixture
      • EF Core InMemory test
      • Integration tests in ASP.NET Core
      • Isolating database data in integration tests
      • Test ASP.NET Core MVC apps
  • Configuration Management
    • Product builds and Continuous Integration
      • Automated build concept
      • Dotnet cli
      • CI/CD Basic concepts
    • Managing Versions
      • Fundamental concepts: revisions, working copy, repository, branch, baseline, trunk
      • Versioning Models
      • Distributed Version Control basics
      • Distributed systems advantages and weak sides
      • VCS Management life-cycle on (one of) major tools (clone, commit, update, revert, merge, resolve, et
      • Branching/Merging strategies
      • Blaming (annotate)
      • Revision graph/log actions (Git)
      • Integrating with Issue Tracking Systems
      • Source control Best Practices
Powered by GitBook
On this page
  • Data types
  • A number
  • A string
  • A boolean (logical type)
  • The “null” value
  • The “undefined” value
  • Objects
  • Symbols
  • The typeof operator
  • Type Conversions
  • ToString
  • ToNumber
  • ToBoolean
  • Summary
  1. Construction Web
  2. JavaScript, HTML, CSS

JavaScript: Data types and types conversion

PreviousJavaScript: VariablesNextJavaScript: Operators

Last updated 5 years ago

Data types

A variable in JavaScript can contain any data. Programming languages that allow such things are called “dynamically typed”, meaning that there are data types, but variables are not bound to any of them.

There are seven basic data types in JavaScript.

  • number for numbers of any kind: integer or floating-point.

  • string for strings. A string may have one or more characters, there’s no separate single-character type.

  • boolean for true/false.

  • null for unknown values – a standalone type that has a single value null.

  • undefined for unassigned values – a standalone type that has a single value undefined.

  • object for more complex data structures.

  • symbol for unique identifiers.

The number type represents both integer and floating point numbers.

There are many operations for numbers, e.g. multiplication *, division /, addition +, subtraction -, and so on.

Besides regular numbers, there are so-called “special numeric values” which also belong to this data type: Infinity, -Infinity and NaN.

NaN is sticky. Any further operation on NaN returns NaN

Infinity represents the mathematical ∞. It is a special value that’s greater than any number.

alert( 1 / 0 ); // Infinity
alert( Infinity ); // Infinity
alert( "not a number" / 2 ); // NaN, such division is erroneous
alert( "not a number" / 2 + 5 ); // NaN

Mathematical operations are safe

Doing maths is “safe” in JavaScript. We can do anything: divide by zero, treat non-numeric strings as numbers, etc.

The script will never stop with a fatal error (“die”). At worst, we’ll get NaN as the result.

A string in JavaScript must be surrounded by quotes. In JavaScript, there are 3 types of quotes:

  1. Double quotes: "Hello".

  2. Single quotes: 'Hello'.

  3. Backticks: `Hello`.

let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed ${str}`;
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)

The expression inside ${…} is evaluated and the result becomes a part of the string. We can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more complex.

Please note that this can only be done in backticks. Other quotes don’t have this embedding functionality!

There is no character type.

In some languages, there is a special “character” type for a single character. For example, in the C language and in Java it is char.

In JavaScript, there is no such type. There’s only one type: string. A string may consist of only one character or many of them.

The boolean type has only two values: true and false.

Boolean values also come as a result of comparisons:

let isGreater = 4 > 1;

alert( isGreater ); // true (the comparison result is "yes")

The special null value does not belong to any of the types described above.

It forms a separate type of its own which contains only the null value:

let age = null;

In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some other languages.

It’s just a special value which represents “nothing”, “empty” or “value unknown”.

The code above states that age is unknown or empty for some reason.

The special value undefined also stands apart. It makes a type of its own, just like null.

The meaning of undefined is “value is not assigned”.

let y;

alert(y); // shows "undefined"

let x = 123;

x = undefined;

alert(x); // "undefined"

…But we don’t recommend doing that. Normally, we use null to assign an “empty” or “unknown” value to a variable, and we use undefined for checks like seeing if a variable has been assigned.

The object type is special. All other types are called “primitive” because their values can contain only a single thing (be it a string or a number or whatever). In contrast, objects are used to store collections of data and more complex entities.

let user = {     // an object
  name: "John",  // by key "name" store value "John"
  age: 30        // by key "age" store value 30
};

The symbol type is used to create unique identifiers for objects. “Symbol” value represents a unique identifier. Upon creation, we can give symbol a description (also called a symbol name), mostly useful for debugging purposes.

Symbols are guaranteed to be unique. Even if we create many symbols with the same description, they are different values. The description is just a label that doesn’t affect anything.

For instance, here are two symbols with the same description – they are not equal:

// id is a new symbol
let id = Symbol();

// id is a symbol with the description "id"
let id = Symbol("id");

let id1 = Symbol("id");
let id2 = Symbol("id");

alert(id1 == id2); // false

The typeof operator

The typeof operator returns the type of the argument. It’s useful when we want to process values of different types differently or just want to do a quick check.

It supports two forms of syntax:

  1. As an operator: typeof x.

  2. As a function: typeof(x).

In other words, it works with parentheses or without them. The result is the same.

The call to typeof x returns a string with the type name:

typeof undefined // "undefined"

typeof 0 // "number"

typeof true // "boolean"

typeof "foo" // "string"

typeof Symbol("id") // "symbol"

typeof Math // "object"  (1)

typeof null // "object"  (2)

typeof alert // "function"  (3)

The typeof operator allows us to see which type is stored in a variable.

  • Two forms: typeof x or typeof(x).

  • Returns a string with the name of the type, like "string".

  • For null returns "object" – this is an error in the language, it’s not actually an object.

Type Conversions

Most of the time, operators and functions automatically convert the values given to them to the right type.

For example, alert automatically converts any value to a string to show it. Mathematical operations convert values to numbers.

String conversion happens when we need the string form of a value.

For example, alert(value) does it to show the value.

We can also call the String(value) function to convert a value to a string:

let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string "true"
alert(typeof value); // string

String conversion is mostly obvious. A false becomes "false", null becomes "null", etc.

Numeric conversion happens in mathematical functions and expressions automatically.

For example, when division / is applied to non-numbers:

alert( "6" / "2" ); // 3, strings are converted to numbers

We can use the Number(value) function to explicitly convert a value to a number:

let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number

Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.

If the string is not a valid number, the result of such a conversion is NaN. For instance:

let age = Number("an arbitrary string instead of a number");

alert(age); // NaN, conversion failed

Numeric conversion rules:

Value

Becomes…

undefined

NaN

null

0

true and false

1 and 0

string

Whitespaces from the start and end are removed. If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN.

Addition ‘+’ concatenates strings

Almost all mathematical operations convert values to numbers. A notable exception is addition +. If one of the added values is a string, the other one is also converted to a string.

Then, it concatenates (joins) them:

alert( 1 + '2' ); // '12' (string to the right)
alert( '1' + 2 ); // '12' (string to the left)

This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers.

Boolean conversion is the simplest one.

It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be performed explicitly with a call to Boolean(value).

The conversion rule:

  • Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.

  • Other values become true.

For instance:

alert( Boolean(1) ); // true
alert( Boolean(0) ); // false

alert( Boolean("hello") ); // true
alert( Boolean("") ); // false

Please note: the string with zero "0" is true

Some languages (namely PHP) treat "0" as false. But in JavaScript, a non-empty string is always true.

alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)

The three most widely used type conversions are to string, to number, and to boolean.

ToString – Occurs when we output something. Can be performed with String(value). The conversion to string is usually obvious for primitive values.

ToNumber – Occurs in math operations. Can be performed with Number(value).

The conversion follows the rules:

Value

Becomes…

undefined

NaN

null

0

true / false

1 / 0

string

The string is read “as is”, whitespaces from both sides are ignored. An empty string becomes 0. An error gives NaN.

ToBoolean – Occurs in logical operations. Can be performed with Boolean(value).

Follows the rules:

Value

Becomes…

0, null, undefined, NaN, ""

false

any other value

true

Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are:

  • undefined is NaN as a number, not 0.

  • "0" and space-only strings like " " are true as a boolean.

A number
Infinity
A string
A boolean (logical type)
The “null” value
The “undefined” value
Objects
Symbols
ToString
ToNumber
ToBoolean
Summary