JavaScript Comparison and Logical Operators - W3Schools

文章推薦指數: 80 %
投票人數:10人

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax. variablename = (condition) ? value1:value2 ... Tutorials References Exercises Videos Menu Login Website GetCertified ProNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C C++ C# R React    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz KotlinQuiz XMLQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro JSTutorial JSHOME JSIntroduction JSWhereTo JSOutput JSStatements JSSyntax JSComments JSVariables JSLet JSConst JSOperators JSArithmetic JSAssignment JSDataTypes JSFunctions JSObjects JSEvents JSStrings JSStringMethods JSStringSearch JSStringTemplates JSNumbers JSNumberMethods JSArrays JSArrayMethods JSArraySort JSArrayIteration JSArrayConst JSDates JSDateFormats JSDateGetMethods JSDateSetMethods JSMath JSRandom JSBooleans JSComparisons JSIfElse JSSwitch JSLoopFor JSLoopForIn JSLoopForOf JSLoopWhile JSBreak JSIterables JSSets JSMaps JSTypeof JSTypeConversion JSBitwise JSRegExp JSErrors JSScope JSHoisting JSStrictMode JSthisKeyword JSArrowFunction JSClasses JSModules JSJSON JSDebugging JSStyleGuide JSBestPractices JSMistakes JSPerformance JSReservedWords JSVersions JSVersions JS2009(ES5) JS2015(ES6) JS2016 JS2017 JS2018 JSIE/Edge JSHistory JSObjects ObjectDefinitions ObjectProperties ObjectMethods ObjectDisplay ObjectAccessors ObjectConstructors ObjectPrototypes ObjectIterables ObjectSets ObjectMaps ObjectReference JSFunctions FunctionDefinitions FunctionParameters FunctionInvocation FunctionCall FunctionApply FunctionBind FunctionClosures JSClasses ClassIntro ClassInheritance ClassStatic JSAsync JSCallbacks JSAsynchronous JSPromises JSAsync/Await JSHTMLDOM DOMIntro DOMMethods DOMDocument DOMElements DOMHTML DOMForms DOMCSS DOMAnimations DOMEvents DOMEventListener DOMNavigation DOMNodes DOMCollections DOMNodeLists JSBrowserBOM JSWindow JSScreen JSLocation JSHistory JSNavigator JSPopupAlert JSTiming JSCookies JSWebAPIs WebAPIIntro WebFormsAPI WebHistoryAPI WebStorageAPI WebWorkerAPI WebFetchAPI WebGeolocationAPI JSAJAX AJAXIntro AJAXXMLHttp AJAXRequest AJAXResponse AJAXXMLFile AJAXPHP AJAXASP AJAXDatabase AJAXApplications AJAXExamples JSJSON JSONIntro JSONSyntax JSONvsXML JSONDataTypes JSONParse JSONStringify JSONObjects JSONArrays JSONServer JSONPHP JSONHTML JSONJSONP JSvsjQuery jQuerySelectors jQueryHTML jQueryCSS jQueryDOM JSGraphics JSGraphics JSCanvas JSPlotly JSChart.js JSGoogleChart JSD3.js JSExamples JSExamples JSHTMLDOM JSHTMLInput JSHTMLObjects JSHTMLEvents JSBrowser JSEditor JSExercises JSQuiz JSCertificate JSReferences JavaScriptObjects HTMLDOMObjects JavaScriptComparisonandLogicalOperators ❮Previous Next❯ ComparisonandLogicaloperatorsareusedtotestfortrueor false. ComparisonOperators Comparisonoperatorsareusedinlogicalstatementstodetermineequalityordifferencebetweenvariablesorvalues. Giventhatx=5,thetablebelowexplainsthecomparisonoperators: Operator Description Comparing Returns Tryit == equalto x==8 false Tryit» x==5 true Tryit» x=="5" true Tryit» === equalvalueandequaltype x===5 true Tryit» x==="5" false Tryit» != notequal x!=8 true Tryit» !== notequalvalueornotequaltype x!==5 false Tryit» x!=="5" true Tryit» x!==8 true Tryit» > greaterthan x>8 false Tryit» < lessthan x<8 true Tryit» >= greaterthanorequalto x>=8 false Tryit» <= lessthanorequalto x<=8 true Tryit» HowCanitbeUsed Comparisonoperatorscanbeusedinconditionalstatementstocomparevalues andtakeactiondependingontheresult: if(age<18)text="Tooyoungtobuyalcohol"; Youwilllearnmoreabouttheuseofconditionalstatementsinthenextchapterofthistutorial. LogicalOperators Logicaloperatorsareusedtodeterminethelogicbetweenvariablesorvalues. Giventhatx=6andy=3,thetablebelowexplainsthelogicaloperators: Operator Description Example Tryit && and (x<10&&y>1)istrue Tryit» || or (x==5||y==5)isfalse Tryit» ! not !(x==y)istrue Tryit» Conditional(Ternary)Operator JavaScriptalsocontainsaconditionaloperatorthatassignsavaluetoavariablebasedonsomecondition. Syntax variablename=(condition)?value1:value2  Example letvoteable=(age<18)?"Tooyoung":"Oldenough"; TryitYourself» Ifthevariableageisavaluebelow18,thevalueofthevariablevoteable willbe"Tooyoung",otherwisethevalueofvoteablewillbe"Oldenough". ComparingDifferentTypes Comparingdataofdifferenttypesmaygiveunexpectedresults. Whencomparingastringwithanumber,JavaScriptwillconvertthestringto anumberwhendoingthecomparison.Anemptystringconvertsto0.Anon-numeric stringconvertstoNaNwhichisalwaysfalse. Case Value Try 2<12 true Tryit» 2"John" false Tryit» 2=="John" false Tryit» "2""12" true Tryit» "2"=="12" false Tryit» Whencomparingtwostrings,"2"willbegreaterthan"12",because (alphabetically)1islessthan2. Tosecureaproperresult,variablesshouldbeconvertedtothepropertype beforecomparison: age=Number(age); if(isNaN(age)){   voteable="Inputisnotanumber"; }else{  voteable=(age<18)?"Tooyoung":"Oldenough"; } TryitYourself» TestYourselfWithExercises Exercise: Choosethecorrectcomparisonoperatortoalerttrue,whenxisgreaterthany. x=10; y=5; alert(xy); SubmitAnswer» StarttheExercise» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?