Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

isMobile

Detects if the current device is a mobile device.

TypeScript
Copied!
1/**
2 * Detects if the current device is a mobile device.
3 *
4 * @returns True if on a mobile device, false otherwise.
5 */
6export function isMobile(): boolean {
7  if (typeof navigator === 'undefined') return false;
8
9  return /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
10    navigator.userAgent
11  );
12}
  • Broad Device Detection

    Recognizes a wide range of mobile platforms including Android, iOS, and legacy devices like BlackBerry and Opera Mini.

  • Simple and Fast

    Performs efficiently with a single regular expression test against navigator.userAgent.

  • Safe in Non-Browser Environments

    Guards against errors in server-side or test environments with a typeof navigator check.

  • No External Dependencies

    Fully self-contained function with zero reliance on third-party packages.

Tests | Examples

TypeScript
Copied!
1const originalUserAgent = navigator.userAgent;
2
3afterEach(() => {
4  Object.defineProperty(navigator, 'userAgent', {
5    value: originalUserAgent,
6    configurable: true,
7  });
8});
9
10test('returns true for Android user agent', () => {
11  Object.defineProperty(navigator, 'userAgent', {
12    value: 'Mozilla/5.0 (Linux; Android 10)',
13    configurable: true,
14  });
15  expect(isMobile()).toBe(true);
16});
17
18test('returns true for iPhone user agent', () => {
19  Object.defineProperty(navigator, 'userAgent', {
20    value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)',
21    configurable: true,
22  });
23  expect(isMobile()).toBe(true);
24});
25
26test('returns false for desktop user agent', () => {
27  Object.defineProperty(navigator, 'userAgent', {
28    value: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
29    configurable: true,
30  });
31  expect(isMobile()).toBe(false);
32});
33
34test('returns false if navigator is undefined', () => {
35  const originalNavigator = globalThis.navigator;
36  delete (globalThis as any).navigator;
37
38  expect(isMobile()).toBe(false);
39
40  globalThis.navigator = originalNavigator;
41});

Common Use Cases

  • Responsive Behavior Control

    Toggle features, layouts, or performance optimizations for mobile users.

  • Mobile-Specific UI Adjustments

    Adjust button sizes, touch targets, or display orientation hints based on device type.

  • Analytics and Usage Metrics

    Log device type for usage statistics, A/B testing, or platform segmentation.

  • Conditional Asset Loading

    Load lighter assets or compressed media for mobile users to improve performance.

Codebase: Utilities -> Platforms -> isMobile | Yevhen Klymentiev