hosam elden hosam elden - 5 months ago 5
Javascript Question

Perform an action based on the page name (Javascript)

I'm trying to get the name of the current page in JS and check if that name matches a constant. If it does, I want to trigger an alert. I'm able to get the name of the page but there's a problem in the if statement and I'm not sure what it is.

<script language="JavaScript">
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
var sHost = 'host.html' ;
if(spage = sHost){


If statement comparison operator should be == or better ===

if(spage == sHost){


if(spage === sHost){

The strict equality operator === only considers values equal that have the same type.

The lenient equality operator == tries to convert values of different types, before comparing like strict equality.

Strict equals === Comparing two values. Values with different types are never equal. If both values have the same type then the following assertions hold.

undefined === undefined
null === null

Two (primitive) numbers:

    NaN !== _  // any value including NaN
    x === x
    +0 === -0

for any number x. Thus equality is not reflexive in JavaScript, because NaN is not equal to itself.

Two booleans, two strings (primitive): obvious results Two objects (including arrays and functions): x === y only if x and y are the same object(!). That is, if you want to compare different objects, you have to do it manually.

Equals == Essentially comparing two values. If both values have the same type then compare with == Otherwise:

undefined == null  

If you have one number, one string: convert the string to a number

A boolean and a non-boolean: convert the boolean to a number and then perform the comparison.

Comparing a string or a number to an object: try to convert the object to a primitive and then make the comparison.